新增文章
文章标题
分类
C#
云星空
K3 BOS
K3 功能
用友
Oracle
python
SQL
MySql
PHP
HTML
script
windows
Access
影视后期
财务
服务
生活
内容
在C#中,我们可以使用以下几种方法来去除字符串中的空格: 方法一:使用正则表达式 string str = " Hello World "; string result = Regex.Replace(str, @"\s+", ""); // 使用正则表达式替换所有空格 Console.WriteLine(result); // 输出:"HelloWorld" 方法二:使用String的Replace方法 string str = " Hello World "; string result = str.Replace(" ", ""); // 使用Replace方法替换空格 Console.WriteLine(result); // 输出:"HelloWorld" 方法三:使用String的Split和Join方法 string str = " Hello World "; string[] words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // 使用Split方法以空格分割字符串,并移除空格 string result = string.Join("", words); // 使用Join方法将分割后的字符串连接起来 Console.WriteLine(result); // 输出:"HelloWorld" 方法四:使用StringBuilder的Append和Replace方法 string str = " Hello World "; StringBuilder sb = new StringBuilder(); foreach (char c in str) { if (!char.IsWhiteSpace(c)) { sb.Append(c); // 逐个字符添加到StringBuilder对象中 } } string result = sb.ToString().Replace(" ", ""); // 使用Replace方法替换空格 Console.WriteLine(result); // 输出:"HelloWorld"
返回
保存