0

我有如下字符串变量

 string pctSign = "\0\0\0";

我想用“%”替换前两个字符

i.e. Final o/p:- pctSign="%\0\0";

如何用 String.Replace 做到这一点?

4

4 回答 4

5
// 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);
于 2012-09-11T11:20:38.420 回答
2

尝试这个:

var pctSign = "\0\0\0";
var result = string.Format("%{0}", pctSign.Substring(2));
于 2012-09-11T11:21:30.210 回答
0
string s = pctSign.Substring(2, pctSign.Length);
s = "%" + s;
于 2012-09-11T11:20:53.313 回答
0

你的意思是只有前两个

pctSign = "%"+pctSign.substring(2);
于 2012-09-11T11:22:10.477 回答