在一个字符串替换多个字符多个、在一、字符串、字符

2023-09-02 21:22:00 作者:喜剧之王

有没有更好的方式来替换字符串?

Is there a better way to replace strings?

我很惊讶,更换并不需要一个字符数组或字符串数​​组。我想,我可以写我自己的扩展,但我很好奇,如果有更好的内置的方法做到以下几点?请注意,最后更换是一个字符串不是字符。

I am surprised that Replace does not take in a character array or string array. I guess that I could write my own extension but I was curious if there is a better built in way to do the following? Notice the last Replace is a string not a character.

myString.Replace(';', 'n').Replace(',', 'n').Replace('r', 'n').Replace('t', 'n').Replace(' ', 'n').Replace("nn", "n");

感谢。

推荐答案

您可以使用替代常规EX pression。

You can use a replace regular expression.

s/[;,tr ]|[n]{2}/n/g

S / 开头意味着搜索 之间的字符 [] 要搜索的字符(以任意顺序) 第二个 / 划定搜索文本和替换文本

s/ at the beginning means a search The characters between [ and ] are the characters to search for (in any order) The second / delimits the search-for text and the replace text

在英国,这个写着:

搜索; t r (空间),或正好两个连续 ñ,并用替换ñ

"Search for ; or , or t or r or (space) or exactly two sequential n and replace it with n"

在C#中,你可以做以下几点:(导入后 System.Text.RegularEx pressions

In C#, you could do the following: (after importing System.Text.RegularExpressions)

Regex pattern = new Regex("[;,tr ]|[n]{2}");
pattern.Replace(myString, "n");
 
精彩推荐
图片推荐