如何替换.NET中第一次出现的子串?

时间:2012-09-11 11:17:08

标签: c# asp.net string replace

我有字符串变量如下

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

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

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

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

4 个答案:

答案 0 :(得分:4)

// 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);

答案 1 :(得分:2)

试试这个:

var pctSign = "\0\0\0";
var result = string.Format("%{0}", pctSign.Substring(2));

答案 2 :(得分:0)

string s = pctSign.Substring(2, pctSign.Length);
s = "%" + s;

答案 3 :(得分:0)

你的意思是前两个

pctSign = "%"+pctSign.substring(2);