[英]How to remove leading and trailing spaces from a string
我有以下输入:
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();
使用修剪方法。
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();
输出是“我是一个字符串”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.