c#字符串中所有的空格可以去掉吗?如何编码实现?

济南云服务器 2024年6月26日08:56:02C#教程c#字符串中所有的空格可以去掉吗?如何编码实现?已关闭评论401阅读模式
在学习c#编程语言时,我们会发现,c#编程语言中使用字符串中的trim方法可以帮助我们去掉字符串中的空格,不过当我们使用该方法解决去掉字符串中空格需求时,并不能将字符串中间位置的空格去掉,那么,news.hcsw666.com/在c#编程语言中还有哪些可以去掉字符串中空格的方法呢?
方法一:使用Trim()方法结合循环
关键代码:
string str = "   h c s w   ";
string result = "";
for (int i = 0; i < str.Length; i++)
{
    if (!Char.IsWhiteSpace(str[i]))
    {
        result += str[i];
    }
}
Console.WriteLine(result); // 输出: hcsw

 

方法二:使用正则表达式
关键代码:
using System.Text.RegularExpressions;

string str = "   h c s w   ";
string result = Regex.Replace(str, @"\s", "");
Console.WriteLine(result); // 输出: hcsw
方法三:使用String.Replace()方法
关键代码:
string str = " h c s w ";
string result = str.Replace(" ", "");
Console.WriteLine(result); // 输出: hcsw
方法四:使用LINQ
关键代码:
using System.Linq;

string str = "   h c s w   ";
string result = new string(str.Where(c => !char.IsWhiteSpace(c)).ToArray());
Console.WriteLine(result); // 输出: hcsw

 

 

济南云服务器
  • 本文由 发表于 2024年6月26日08:56:02
  • 转载请务必保留本文链接:http://news.hcsw666.com/1338