
在 C# 中,有多种方法可以用单个空格替换多个空格。
String.Replace - 返回一个新字符串,其中所有出现的指定 Unicode 字符或字符串将当前字符串中的内容替换为另一个指定的 Unicode 字符或字符串。
Replace(String, String, Boolean, CultureInfo)
String.Join 连接指定数组的元素或集合的成员,在每个元素或成员之间使用指定的分隔符。
Regex.Replace - 在指定的输入字符串中,替换匹配的字符串具有指定替换字符串的正则表达式模式。
使用正则表达式的示例 -
网页中拖动 DIV 是很常见的操作,今天就分享给大家一个 jQuery 多列网格拖动布局插件,和其它的插件不太一样的地方在于你处理拖放的元素支持不同大小,并且支持多列的网格布局,它们会自动的根据位置自己排序和调整。非常适合你开发具有创意的应用。这个插件可以帮助你将任何的 HTML 元素转换为网格组件
74
实时演示
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 Everyone String 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 Everyone String with single space: Hello World. Hi Everyone
在上面,我们使用 Split 方法将文本拆分为多个空格, 稍后使用 Join 方法用单个空格连接分割后的数组。
以上就是如何在 C# 中将多个空格替换为单个空格?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号