如何在C#.NET中用空字符替换字符串中的char


78

我有一个像这样的字符串:

string val = "123-12-1234";

如何在C#中使用空字符串替换破折号。

我的意思是 val.Replace(char oldChar, newChar);

有什么需要去oldCharnewChar


3
字符串val =“ 123-12-1234” .Replace(“-”,String.Empty); //注意:请至少在发布问题之前尝试解决问题。
Brandon Moretz

9
为什么要投票?回答这个问题可能很简单,但是肯定不会出错吗?新用户可能很快就会灰心……
Peter Kelly

5
同意彼得·凯利(Peter Kelly)-赞成
尼克(Nick)


5
有人介意解释为什么关闭得太局限了吗?
Xeo

Answers:


127

您可以使用该Replace()字符串的其他重载。

val = val.Replace("-", string.Empty)

2
+1表示替代方法是“过载”
尼克

尝试使用上述重载替换\ 0字符,它将不起作用!\ 0字符将不会被替换。从SNMP设备接收到的字符串数据时,尤其如此
史蒂夫·约翰逊

1
为什么char到char替换重载不能在这里工作的原因-为什么没有String.Empty这样的Char.Empty?
英国广播公司

我有一个变量代替上面的“-”,并在其位置使用了charToReplace.ToString()。
Zonus

44

由于此处的其他答案(即使是正确的)也没有明确解决您最初的疑问,因此我会做。

如果调用string.Replace(char oldChar, char newChar),它将用另一个字符替换一个字符的出现。它是一对一的替代品。因此,结果字符串的长度将相同。

您想要的是删除破折号,这显然与用另一个字符替换破折号不同。您不能将其替换为“无字符”,因为1个字符始终是1个字符。这就是为什么您需要使用带字符串的重载:字符串可以具有不同的长度。如果将长度为1的字符串替换为长度为0的字符串,则结果是破折号消失了,由“ nothing”代替。


3
感谢您提供详细的解释。
2011年

1
毕竟,您没有演示。:P哦,很好。无论如何+1来解释
cHao

1
您可以在此处找到更多信息。
Dinei




3

如果要用空字符替换字符串中的字符,这意味着要从字符串中删除该字符,请阅读R. Martinho Fernandes的答案。

这是一个如何从字符串中删除字符的示例(用“空字符”代替):

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar >= 0)
        {
            input = input.Remove(indexOfChar, 1);
        }
        return input;
    }

或此版本删除字符串中所有char重复出现的版本:

    public static string RemoveCharFromString(string input, char charItem)
    {
        int indexOfChar = input.IndexOf(charItem);
        if (indexOfChar < 0)
        {
            return input;
        }
        return RemoveCharFromString(input.Remove(indexOfChar, 1), charItem);
    }

1

如果您处于循环中,假设您遍历要删除的标点符号列表,则可以执行以下操作:

      private const string PunctuationChars = ".,!?$";
          foreach (var word in words)
                {
                    var word_modified = word;

                    var modified = false;

                    foreach (var punctuationChar in PunctuationChars)
                    {
                        if (word.IndexOf(punctuationChar) > 0)
                        {
                            modified = true;
                            word_modified = word_modified.Replace("" + punctuationChar, "");


                        }
                    }
               //////////MORE CODE
               }

诀窍如下:

word_modified.Replace("" + punctuationChar, "");

1

我有Razvan Dumitru的拉丁语代码版本,因为我们甚至使用了100万个指标。场外我用双重替换:D

public static string CleanNumb(string numb) 
{
    foreach (char c in ".,'´")
       numb = numb.Replace(c, ' ');

    return numb.Replace(" ", "");
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.