I have the string string test="http://www.test.com//web?testid=12".
I need to replace with in the string // into /.
Problem is if I use string a=test.replace("//","/") I get http:/www.test.com/web?testid=12 all with single slash(/) but I need http://www.test.com/web?testid=12.
I need only the second // nearby web, not first // near by www.
How to do this?
You can make second replace
string test="http://www.test.com//web?testid=12";
string a=test.Replace("//","/").Replace("http:/","http://");
=)
string test = #"http://www.test.com//web?testid=12";
test = test.Substring(0, test.LastIndexOf(#"//") - 1)
+ test.Substring(test.LastIndexOf(#"//")).Replace(#"//", #"/");
Or since its a Uri, you can do:
Uri uri = new Uri(test);
string newTest = uri.Scheme + #"//" + uri.Authority
+ uri.PathAndQuery.Replace(#"//",#"/");
string test="http://www.test.com//web?testid=12"
string[] test2 = test.Split('//');
string test = test2[0] + "//" + test2[1] + "/" + test2[2];
Regex.Replace(test, "[^:]//", "/");
you can use stringbuilder as well.
StringBuilder b =new StringBuilder();
b.Replace("/","//",int startindex,int count);
Simply remove one of the last slashes with String.Remove():
string test="http://www.test.com//web?testid=12";
string output = test.Remove(test.LastIndexOf("//"), 1);
var http = "http://someurl//data";
var splitindex = http.IndexOf("/") + 1;
var res = http.Substring(splitindex+1, (http.Length-1) - splitindex).Replace("//","/");
http = "http://" + res;
Or
StringBuilder strBlder = new StringBuilder();
strBlder.Append("http://someurl//data");
//use the previously used variable splitindex
strBlder.Replace("//", "/", splitindex + 1, (http.Length) - splitindex);
Related
I need to insert in a specific position of the string line, another string, so I compute the specific position for start to insert:
string info1 = "info1";
string info2 = "info2";
string info3 = "info3";
string info4 = "info4";
string keyWord = "BELEGIT";
start = line.IndexOf(keyWord, 0) + keyWord.Length + 13;
var aStringBuilder = new StringBuilder(line);
aStringBuilder.Remove(start, 19);
line = aStringBuilder.ToString();
string newLine = line.Insert(start, "\r\n" + info1 + "\r\n" + "\r\n" + info2 + "\r\n" + info3 + "\r\n" + info4 + "\r\n");
(newLine will be the content of a file in my application).
newline contains the correct content except the string "00000" that inserts after "info4". So in my new file with the content that is newline there is newline and immediately after "00000". I do not really understand why.
Thanks in advance.
INPUT:
line contains:
#~11\r\nT-02040121R\r\n\r\n\r\n\r\n\r\n\r\n\n2.000000000\r\n
OUTPUT
newLine contains:
#~11\r\nT-02040121R\r\ninfo1\r\n\r\ninfo2\r\ninfo3\r\ninfo4\r\n00000\r\n
Assuming that you want just the first 19 chars of lineyou could use Substringto get them and string.Formatto build the new string.
Something like this
var start = line.Substring(0, 19);
string newLine = $"{start}\r\n{info1}\r\n\r\n{info2}\r\n{info3}\r\n{info4}\r\n";
The second line is the short form for
string newLine = string.Format("{0}\r\n{1}\r\n\r\n{2}\r\n{3}\r\n{4}\r\n", start, info1, info2, info3, info4);
if you need more information about string.Formathave a look at the MSDN.
I have an array of string values obtained from a method and I want to convert this array into a HTML readable format for getting/posting (eg. value=[12,21])
I have tried the following:
string[] array1 = methodToGetStringArray(); //assuming [12,21] for example
string finalString = "value="+array1; //intended output is value=[12,21]
Which of course doesn't work.
I would like to know the method to provided the value as shown above.
You can try,
string finalString = String.Format("value=[{0}]", string.Join(", ", array1));
finalString should return,
value=[12, 21]
Try like this:
string[] array1 = methodToGetStringArray();
string json = JsonConvert.SerializeObject(array1);
Refer JSON.NET
you can try this
string finalString = "Value = [" + string.Join(",", array1) + "]";
Use string.Join method:
string finalString = "value=[" + string.Join(",",array1) + "]";
Or JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
var finalString = "value=" + serializer.Serialize(array1);
List<string> list = new List<string>(array1);
var a = "value=[" + list.Aggregate((x, y) => x + "," + y) + "]";
When i program,i want to delete a specify string in a long string.
For example:
The source string is:
abcdffff<fdfs>adbcccc
abcdffff<fdferfefs>adbcccc
abcdffff<fdffefes>adbcccc
abcdffff<fdffefefs>adbcccc
The i want to delete the string like <fdfs>
The result should be:
abcdffffadbcccc
abcdffffadbcccc
abcdffffadbcccc
abcdffffadbcccc
How could i do?
This is my code:
public string formatMailMessageBody(string herf,string notifyinfo)
{
StringBuilder sb = new StringBuilder();
sb.Append(notifyinfo.Replace("〈%〉", "") + "<br><br>");
sb.Append("单击下面的链接查看您当前任务:<br>");
sb.Append("<a href='" + herf + "'><b>" + herf + "</b></a>");
string s = sb.ToString();
return sb.ToString();
}
Is it right?
Note that the following code is applicable only if the string you want to delete has this format <...> (no other pairs of <> inside):
var output = Regex.Replace(input, #"\<[^>]*\>", "");
The Regex class is located in the namespace System.Text.RegularExpressions.
Getting this error The given path's format is not supported. at this line
System.IO.Directory.CreateDirectory(visit_Path);
Where I am doing mistake in below code
void Create_VisitDateFolder()
{
this.pid = Convert.ToInt32(db.GetPatientID(cmbPatientName.SelectedItem.ToString()));
String strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = strpath + "\\Patients\\Patient_" + pid + "\\";
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string visit_Path = path +"visit_" + visitNo + "_" + visitdate+"\\";
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
if (!IsVisitExist)
{
System.IO.Directory.CreateDirectory(path);
}
if (!IsVisitPath)
{
System.IO.Directory.CreateDirectory(visit_Path);\\error here
}
}
getting this value for visit_Path
C:\Users\Monika\Documents\Visual Studio 2010\Projects\SonoRepo\SonoRepo\bin\Debug\Patients\Patient_16\visit_4_16-10-2013 00:00:00\
You can not have : in directory name, I suggest you to use this to string to get date in directory name:
DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss");
it will create timestamp like:
2013-10-17 05_41_05
additional note:
use Path.Combine to make full path, like:
var path = Path.Combine(strpath , "Patients", "Patient_" + pid);
and last
string suffix = "visit_"+visitNo+"_" + visitdate;
var visit_Path = Path.Combine(path, suffix);
In general always use Path.Combine to create paths:
String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = Path.Combine(strPath,"Patients","Patient_" + pid);
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string fileName = string.Format("visit_{0}_{1}", visitNo, visitdate);
string visit_Path = Path.Combine(path, fileName);
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
To replace invalid characters from a filename you could use this loop:
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
visit_Path = visit_Path.Replace(c.ToString(), ""); // or with "."
}
You can't have colons : in file paths
You can't use colons (:) in a path. You can for example Replace() them with dots (.).
Just wanted to add my two cents.
I assigned the path from a text box to string and also adding additional strings, but I forgot to add the .Text to the text box variable.
So instead of
strFinalPath = TextBox1.Text + strIntermediatePath + strFilename
I wrote
strFinalPath = TextBox1 + strIntermediatePath + strFilename
So the path became invalid because it contained invalid characters.
I was surprised that c# instead of rejecting the assignment because of type mismatch, assigned invalid value to the final string.
So look at the path assignment string closely.
I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}