[英]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.