如何删除字符串中的前导和尾随空格

问题描述:

我有以下输入:

string txt = "                   i am a string                                    "

我想从一个字符串开始和结束的开始删除空间。

I want to remove space from start of starting and end from a string.

结果应该是:我是一个字符串

如何在C#中做到这一点

How can I do this in c#?

String.Trim

删除所有开头和结尾从当前String对象的空白字符

Removes all leading and trailing white-space characters from the current String object.

用法:

txt = txt.Trim();

如果这是不工作的话就很有可能是空间不是空格但一些其他非打印或空白字符,可能是标签。在这种情况下,你需要使用 String.Trim 方法,需要一个字符数组:

If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

  char[] charsToTrim = { ' ', '\t' };
  string result = txt.Trim(charsToTrim);

来源

,当你遇到更多的空间,像他这样在输入数据字符您可以添加到这个列表。存储在数据库或配置文件中的字符这个名单也意味着您不必在每次遇到一个新的角色来检查的时间来重新构建应用程序。

You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.