在 c# 中,有多种方法可以用单个空格替换多个空格。
string.replace - 返回一个新字符串,其中所有出现的指定 unicode 字符或字符串将当前字符串中的内容替换为另一个指定的 unicode 字符或字符串。
replace(string, string, boolean, cultureinfo)
string.join 连接指定数组的元素或集合的成员,在每个元素或成员之间使用指定的分隔符。
regex.replace - 在指定的输入字符串中,替换匹配的字符串具有指定替换字符串的正则表达式模式。
使用正则表达式的示例 -
示例 实时演示
using system;using system.text.regularexpressions;namespace demoapplication{ class program{ public static void main(){ string stringwithmuliplespaces = "hello world. hi everyone"; console.writeline($"string with multiples spaces: {stringwithmuliplespaces}"); string stringwithsinglespace = regex.replace(stringwithmuliplespaces, @"\s+", " "); console.writeline($"string with single space: {stringwithsinglespace}"); console.readline(); } }}
输出上述程序的输出为
string with multiples spaces: hello world. hi everyonestring with single space: hello world. hi everyone
在上面的示例 regex.replace 中,我们已经确定了额外的空格和替换为单个空格
使用 string.join 的示例 -
示例 实时演示
using system;namespace demoapplication{ class program{ public static void main(){ string stringwithmuliplespaces = "hello world. hi everyone"; console.writeline($"string with multiples spaces: {stringwithmuliplespaces}"); string stringwithsinglespace = string.join(" ", stringwithmuliplespaces.split(new char[] { ' ' }, stringsplitoptions.removeemptyentries)); console.writeline($"string with single space: {stringwithsinglespace}"); console.readline(); } }}
输出上述程序的输出为
string with multiples spaces: hello world. hi everyonestring with single space: hello world. hi everyone
在上面,我们使用 split 方法将文本拆分为多个空格,稍后使用 join 方法用单个空格连接分割后的数组。
以上就是如何在 c# 中将多个空格替换为单个空格?的详细内容。