如何删除字符串中的前导和尾随空格 [英] How to remove leading and trailing spaces from a string

查看:1244
本文介绍了如何删除字符串中的前导和尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入:

string txt = "                   i am a string                                    "

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

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

结果应该是:<?code>我是一个字符串

如何在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.

这篇关于如何删除字符串中的前导和尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆