如何从句子中去掉空格

本文关键字:空格 句子 | 更新日期: 2023-09-27 17:50:16

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

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

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

如何从句子中去掉空格

方法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"

试试这个

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

或者使用Regex

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