【发布时间】:2010-08-17 11:08:06
【问题描述】:
我有以下输入:
string txt = " i am a string "
我想从字符串的开头和结尾删除空格。
结果应该是:"i am a string"
如何在 c# 中做到这一点?
【问题讨论】:
我有以下输入:
string txt = " i am a string "
我想从字符串的开头和结尾删除空格。
结果应该是:"i am a string"
如何在 c# 中做到这一点?
【问题讨论】:
从当前 String 对象中删除所有前导和尾随空白字符。
用法:
txt = txt.Trim();
如果这不起作用,那么“空格”很可能不是空格,而是其他一些非打印或空白字符,可能是制表符。在这种情况下,您需要使用 String.Trim 方法,该方法采用字符数组:
char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);
当您遇到更多空格(例如输入数据中的字符)时,您可以添加到此列表中。将此字符列表存储在数据库或配置文件中还意味着您不必在每次遇到要检查的新字符时都重新构建应用程序。
注意
从 .NET 4 开始,.Trim() 删除了Char.IsWhiteSpace 返回true 的任何字符,因此它应该适用于您遇到的大多数情况。鉴于此,将这个调用替换为需要您必须维护的字符列表的调用可能不是一个好主意。
最好调用默认的.Trim(),然后然后用你的字符列表调用方法。
【讨论】:
你可以使用:
用法:
string txt = " i am a string ";
char[] charsToTrim = { ' ' };
txt = txt.Trim(charsToTrim)); // txt = "i am a string"
编辑:
txt = txt.Replace(" ", ""); // txt = "iamastring"
【讨论】:
我真的不明白其他答案正在跳过的一些箍。
var myString = " this is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";
这不是火箭科学。
【讨论】:
txt = txt.Trim();
【讨论】:
或者您可以将字符串拆分为字符串数组,按空格拆分,然后将字符串数组的每一项添加到空字符串中。
可能这不是最好和最快的方法,但如果其他答案不是您想要的,您可以尝试。
【讨论】:
text.Trim() 将被使用
string txt = " i am a string ";
txt = txt.Trim();
【讨论】:
使用 Trim 方法。
【讨论】:
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(@"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, @" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, @" ");
Console.WriteLine(s4);
Console.ReadLine();
}
输出:
他看到了一只可爱的狗。 还有一句话。 他看到了一只可爱的狗。
【讨论】:
你可以使用
string txt = " i am a string ";
txt = txt.TrimStart().TrimEnd();
输出是“我是一个字符串”
【讨论】: