I am having string variable as follow
string pctSign = "\0\0\0";
I want to replace first two characters with "%"
i.e. Final o/p:- pctSign="%\0\0";
How to do this with String.Replace?
I am having string variable as follow
string pctSign = "\0\0\0";
I want to replace first two characters with "%"
i.e. Final o/p:- pctSign="%\0\0";
How to do this with String.Replace?
// Option 1
var result = "%" + pctSign.Remove(0, 2);
// Option 2
var result = "%" + pctSign.Substring(2);
// Option 3
var regex = new Regex("^\\0");
var result = regex.Replace(pctSign, "%");
If you absolutely want to user String.Replace()
then you can write your own extension method:
public static class StringExtension
{
public static String Replace(this string self,
string oldString, string newString,
bool firstOccurrenceOnly = false)
{
if ( !firstOccurrenceOnly )
return self.Replace(oldString, newString);
int pos = self.IndexOf(oldString);
if ( pos < 0 )
return self;
return self.Substring(0, pos) + newString
+ self.Substring(pos + oldString.Length);
}
}
// Usage:
var result = pctSign.Replace("/0", "%", true);
Try this:
var pctSign = "\0\0\0";
var result = string.Format("%{0}", pctSign.Substring(2));
you mean only first two then
pctSign = "%"+pctSign.substring(2);