如何使用C#在字符串中的第一个数值后用指定的字符替换空格/字符?

时间:2013-07-31 14:25:31

标签: c# str-replace

String包含Special Characters & Numeric Values

Eg:
3-3 3 
3-3"3/4
3-3-3/4
3-3 3/4
3 3 3
3'3 3

Output must be:
    3f3 3 
    3f3"3/4
    3f3-3/4
    3f3 3/4
    3f3 3
    3f3 3

我尝试过使用:

public static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);
            if (pos < 0)
            {
                return text;
            }
            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }

使用上面的代码,它用指定的字符替换第一次出现,这很好。

Eg: 3-3 3 Output: 3f3 3

但是对于3 3-3 Output: 3 3f3根据代码是正确的。但我想在第一个数字后替换空格/字符3f3-3

帮助感谢!

3 个答案:

答案 0 :(得分:0)

var match = Regex.Match(text, search); //To search for any special character, use @"\W" as the second parameter
var editable = text.ToCharArray();
editable[match.Index] = replace[0];
text = new String(editable);
return text;

答案 1 :(得分:0)

简单循环应该有效。

for(int i =0; i < myListOfStrings.Count; i++)
{
    char[] chars = myListOfStrings[i].ToCharArray();
    for (int j = 0; j < chars.Count(); j++)
    {
       if (Char.IsDigit(chars[j]))
       {
           if(j + 1 < chars.Count())
           {
              chars[j + 1] = 'f'; //'f' being your replacing character
              myListOfStrings[i] = new string(chars);
           }
           break;
       }
    }
}

输出示例

myListOfStrings.Add("3-3 3");
myListOfStrings.Add("3-3-3/4");
myListOfStrings.Add("3 3-3");
myListOfStrings.Add("3 3 3");

3f3 3
3f3-3/4
3f3-3
3f3 3

从评论中更新

for (int i = 0; i < myListOfStrings.Count; i++)
{
     char[] chars = myListOfStrings[i].ToCharArray();
     for (int j = 0; j < chars.Count(); j++)
     {
         if (!Char.IsDigit(chars[j]))
         {
             if (j + 1 < chars.Count())
             {
                 chars[j] = 'f'; //'f' being your replacing character
                 myListOfStrings[i] = new string(chars);
             }
             break;
         }
     }
}

答案 2 :(得分:0)

以下为我工作:

修改后的代码:

string S="10-3 3";
char[] chars = S.ToCharArray();
                for (int j = 0; j < chars.Count(); j++)
                {
                    if (Char.IsDigit(chars[j]))
                    {

                    }
                    else
                    {
                        if (j + 1 < chars.Count())
                        {
                            chars[j] = 'f'; //'f' being  replacing character
                            S = new string(chars);
                        }
                        break;
                    }
                }

Output: 10f3 3