【问题标题】:How to remove white spaces from sentence?如何从句子中删除空格?
【发布时间】:2014-04-20 08:12:00
【问题描述】:

我想从包含句子的字符串变量中删除所有空格。 这是我的代码:

string s = "This text contains white spaces";
string ns = s.Trim();

变量“sn”应该看起来像“Thistextcontainswhitespaces”,但它不是(方法 s.Trim() 不起作用)。我错过了什么或做错了什么?

【问题讨论】:

  • 这是什么语言?
  • 语言是什么?
  • 我用的是c#语言
  • Trim 方法从当前字符串中删除所有前导和尾随空白字符。前导空白字符是出现在字符串中所有非空白字符之前的空白字符。尾随空白字符是出现在字符串中所有非空白字符之后的空白字符。对字符串“this is”调用 Trim() 将返回“this is”。
  • 也检查此链接http://stackoverflow.com/questions/5203607/fastest-way-to-remove-white-spaces-in-string

标签: c# trim removing-whitespace


【解决方案1】:

Trim 方法通常只是删除字符串开头和结尾的空格。

string s = "     String surrounded with whitespace     ";
string ns = s.Trim();

将创建此字符串:"String surrounded with whitespace"

要从字符串中删除所有空格,请使用Replace 方法:

string s = "This text contains white spaces";
string ns = s.Replace(" ", "");

这将创建这个字符串:"Thistextcontainswhitespaces"

【讨论】:

    【解决方案2】:

    试试这个。

    s= s.Replace(" ", String.Empty);
    

    或者使用正则表达式

    s= Regex.Replace(s, @"\s+", String.Empty);
    

    【讨论】:

    • 我推荐String.Replace,如果你知道空格总是一个空格字符(ASCII 32)。正则表达式的开销要大得多。
    猜你喜欢
    • 2013-01-12
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2020-01-15
    相关资源
    最近更新 更多