按字符串修剪字符串

时间:2012-04-17 08:43:25

标签: c#

如何用整个字符串而不是单个字符列表修剪字符串?

我想删除HTML字符串开头和结尾的所有 和空格。但方法String.Trim()只对字符集有重载,而对字符串集只有重载。

4 个答案:

答案 0 :(得分:8)

您可以使用HttpUtility.HtmlDecode(String)并将结果用作String.Trim()

的输入

HttpUtility.HtmlDecode on MSDN
HttpServerUtility.HtmlDecode on MSDN(您可以通过Page.Server属性访问的包装器)

string stringWithNonBreakingSpaces;
string trimmedString =  String.Trim(HttpUtility.HtmlDecode(stringWithNonBreakingSpaces));

注意:此解决方案会解码输入中的所有HTML字符串。

答案 1 :(得分:2)

Trim方法默认从当前字符串中删除所有前导和尾随空白字符。

编辑:编辑后问题的解决方案:

string input = @"  &nbsp; <a href='#'>link</a>  &nbsp; ";
Regex regex = new Regex(@"^(&nbsp;|\s)*|(&nbsp;|\s)*$");
string result = regex.Replace(input, String.Empty);

这将删除所有尾随和前导空格以及&nbsp;。您可以向表达式添加任何字符串或字符组。如果您要修剪所有选项卡,正则表达式将简单地变为:

Regex regex = new Regex(@"^(&nbsp;|\s|\t)*|(&nbsp;|\s|\t)*$");

答案 2 :(得分:1)

不确定这是否是您要找的?

   string str = "hello &nbsp;";
   str.Replace("&nbsp;", "");
   str.Trim();

答案 3 :(得分:1)

使用RegEx,正如 David Heffernan 所说。在字符串开头选择所有空格非常容易:^(\ |&nbsp;)*

相关问题