在一个字符串替换多个字符 [英] Replace Multiple Characters in a String
问题描述
有没有更好的方式来替换字符串?
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("\n\n", "\n");
感谢。
推荐答案
您可以使用替代常规EX pression。
You can use a replace regular expression.
s/[;,\t\r ]|[\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("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");
这篇关于在一个字符串替换多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!