如何去掉中间的空格?

dvdvip 2008-04-02 09:10:15
用户在输入内容时,很可以在句子里面插入很多空格。用Trim方法是去不掉这样的空格的。例如:


This is the Apple iPhone.

变成:

This is the Apple iPhone.


ASP。NET里面有什么好方法可以去掉这样的多余空格?连续两个以上的就算是多余。

谢谢了。
...全文
261 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
JL99000 2008-04-02
  • 打赏
  • 举报
回复
private string DeleteSpace(string s)
{
string result = "";
int i = s.IndexOf(" ");
string nowStr = s;
while (i > 0)
{
result = result + nowStr.Substring(0, i) + " ";
nowStr = nowStr.Substring(i).Trim();
i = nowStr.IndexOf(" ");
}
return result.Trim();
}
写了一个小方法,去掉多余空格
rohan 2008-04-02
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 hbxtlhx 的回复:]
引用 5 楼 rohan 的回复:
引用 1 楼 whycom 的回复:
Regex.Replace( inputstring ,"\\s+" , " ");

这个最好!


可以吗?除非也是写一个循环来操作!
[/Quote]
可以呀,正则的话加个全局参数/g就行了
wolf_410 2008-04-02
  • 打赏
  • 举报
回复
1楼的正解!!UP
北京的雾霾天 2008-04-02
  • 打赏
  • 举报
回复
不好意思,又回错了一次,我说的是这个:

[Quote=引用 6 楼 heerxiong 的回复:]
String.Replace(被替换的字符串,要替换的内容);
[/Quote]

fcuandy 2008-04-02
  • 打赏
  • 举报
回复
可以的, 1楼是用正则来替换。
北京的雾霾天 2008-04-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 rohan 的回复:]
引用 1 楼 whycom 的回复:
Regex.Replace( inputstring ,"\\s+" , " ");

这个最好!
[/Quote]

可以吗?除非也是写一个循环来操作!
heerxiong 2008-04-02
  • 打赏
  • 举报
回复
String.Replace(被替换的字符串,要替换的内容);
rohan 2008-04-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 whycom 的回复:]
Regex.Replace( inputstring ,"\\s+" , " ");
[/Quote]
这个最好!
netfeel2008 2008-04-02
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 hbxtlhx 的回复:]
我写了两个苯方法:

C# code
private string TrimStringA(string str)
{
string _str = null;
bool empty = false;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
{
empty = true;
}
else
{
if (empty)
{
_str += " " + str[i];
}
else

[/Quote]
up
北京的雾霾天 2008-04-02
  • 打赏
  • 举报
回复
我写了两个苯方法:

private string TrimStringA(string str)
{
string _str = null;
bool empty = false;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
{
empty = true;
}
else
{
if (empty)
{
_str += " " + str[i];
}
else
{
_str += str[i];
}
empty = false;
}
}
if (empty)
{
_str += " ";
}
return _str;
}



private string TrimStringB(string str)
{
string _str = null;
string[] s = str.Split(' ');
for (int i = 0; i < s.Length; i++)
{
if (s[i] != string.Empty)
{
_str += s[i] + " ";
}
}
if (_str != null && _str.EndsWith(" "))
{
_str = _str.Substring(0, _str.Length - 1);
}
return _str;
}


使用上:

string str = " This is the Apple iPhone.";
string _str=TrimStringA(str);
string _str1 = TrimStringB(str);


yanglongyy 2008-04-02
  • 打赏
  • 举报
回复
s.Replace(" "," ")这样不就可以了吗 很简单的啊
whycom 2008-04-02
  • 打赏
  • 举报
回复
Regex.Replace( inputstring ,"\\s+" , " ");

62,039

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧