簡體   English   中英

如何在C#中刪除字符串的第一個和最后一個字符?

[英]How to remove first and last character of a string in C#?

String: "hello to the very tall person I am about to meet"

我想讓它變成這樣:

String: hello to the very tall person I am about to meet

我只能找到代碼來修剪開始?

使用 String.Substring 方法。

因此,如果您的字符串存儲在變量mystr ,請執行以下操作:

mystr = mystr.Substring(1, mystr.Length - 2);

如果您想從字符串中刪除任何第一個和最后一個字符,請按照 Anish 的建議使用 Substring,但如果您只想從開頭和結尾刪除引號,只需使用

myStr = myStr.Trim('"');

注意:這將刪除所有前導和尾隨引號 ( docs )。

如果您嘗試從字符串中刪除特定字符,例如示例中的引號,您可以使用Trim進行開始和結束修剪,或者如果您想從開始和結束修剪不同的字符,則可以使用TrimStartTrimEnd 將要從字符串開頭和結尾刪除的字符(或字符數組)傳遞給這些方法。

var quotedString = "\"hello\"";
var unQuotedString = quotedString.TrimStart('"').TrimEnd('"'); 

// If the characters are the same, then you only need one call to Trim('"'):
unQuotedString = quotedString.Trim('"');

Console.WriteLine(quotedString);
Console.WriteLine(unQuotedString);

輸出:

“你好”

你好

或者,您可以使用Skip and TakeConcat從字符串的開頭和結尾刪除字符。 這甚至適用於空字符串,讓您無需擔心計算字符串長度:

var original = "\"hello\"";
var firstAndLastRemoved = string.Concat(original.Skip(1).Take(original.Length - 2));

C# 8: myString[1..^1]
查看指數和范圍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM