0

我有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

帮助赞赏!

4

3 回答 3

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;
于 2013-07-31T14:35:04.140 回答
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;
         }
     }
}
于 2013-07-31T14:44:40.250 回答
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
于 2013-08-01T09:18:13.183 回答