我有如下字符串变量
string pctSign = "\0\0\0";
我想用“%”替换前两个字符
i.e. Final o/p:- pctSign="%\0\0";
如何用 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, "%");
如果您绝对想要用户,String.Replace()
那么您可以编写自己的扩展方法:
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);
尝试这个:
var pctSign = "\0\0\0";
var result = string.Format("%{0}", pctSign.Substring(2));
string s = pctSign.Substring(2, pctSign.Length);
s = "%" + s;
你的意思是只有前两个
pctSign = "%"+pctSign.substring(2);