簡體   English   中英

修剪字符串中的最后一個字符

[英]Trim last character from a string

我有一個字符串說

"Hello! world!" 

我想修剪或移除以取出 ! 離世界但不離你好。

"Hello! world!".TrimEnd('!');

閱讀更多

編輯:

我在這類問題中注意到,幾乎每個人都建議刪除給定字符串的最后一個字符。 但這並不滿足 Trim 方法的定義。

修剪 - 從此實例的開頭和結尾刪除所有出現的空白字符。

MSDN-修剪

在這個定義下,只從字符串中刪除最后一個字符是不好的解決方案。

所以如果我們想“從字符串中修剪最后一個字符”,我們應該做這樣的事情

擴展方法示例:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

請注意,如果您想刪除所有具有相同值的字符,即(!!!!)上面的方法將刪除所有存在的 '!' 從字符串的末尾,但如果你只想刪除最后一個字符,你應該使用這個:

else { return str.Remove(str.Length - 1); }
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
if (yourString.Length > 1)
    withoutLast = yourString.Substring(0, yourString.Length - 1);

或者

if (yourString.Length > 1)
    withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);

...如果您想從末尾刪除非空白字符。

string s1 = "Hello! world!";
string s2 = s1.Trim('!');

從字符串中修剪最后一個字符的另一個示例:

string outputText = inputText.Remove(inputText.Length - 1, 1);

您可以將其放入擴展方法中並防止它出現空字符串等。

嘗試這個:

return( (str).Remove(str.Length-1) );
string helloOriginal = "Hello! World!";
string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
string s1 = "Hello! world!"
string s2 = s1.Substring(0, s1.Length - 1);
Console.WriteLine(s1);
Console.WriteLine(s2);

在 .NET 5 / C# 8 中:

您可以將標記為答案的代碼編寫為:

public static class StringExtensions
{
    public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}

但是,如答案中所述,這將刪除最后一個字符的所有出現。 如果您只想刪除最后一個字符,您應該這樣做:

    public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];

對 C# 8 中新內容的快速解釋:

^稱為“來自結束運算符的索引”。 ..被稱為“范圍運算符”。 ^1arr.length - 1的快捷方式。 您可以使用arr[1..]數組第一個字符之后的所有項目,或者使用arr[..^1]獲取最后一個字符之前的所有項目。 這些只是幾個簡單的例子。 有關詳細信息,請參閱https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8 ,“指數和范圍”部分。

你也可以使用這個:

public static class Extensions
 {

        public static string RemovePrefix(this string o, string prefix)
        {
            if (prefix == null) return o;
            return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
        }

        public static string RemoveSuffix(this string o, string suffix)
        {
            if(suffix == null) return o;
            return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
        }

    }

非常簡單:

str = str.Remove( str.Length - 1 );

簡化此操作的示例擴展類:-

internal static class String
{
    public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
    public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
    public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;

    private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}

用法

"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)

"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something'  (End Characters removed)

"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!'  (Only End instances removed)

@Damian Leszczyński 的輕微修改版本 - Vash 將確保僅刪除特定字符。

public static class StringExtensions
{
    public static string TrimLastCharacter(this string str, char character)
    {
        if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
        {
            return str;
        }
        return str.Substring(0, str.Length - 1);
    }
}

我選擇了使用 TrimEnd 編寫擴展的路徑,只是因為我已經在內聯使用它並且對它感到滿意......即:

static class Extensions
{
        public static string RemoveLastChars(this String text, string suffix)
        {            
            char[] trailingChars = suffix.ToCharArray();

            if (suffix == null) return text;
            return text.TrimEnd(trailingChars);
        }

}

確保使用靜態類 ;P 在類中包含命名空間,用法是:

string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          

如果要刪除“!” 來自特定表達式的字符(在您的情況下為“world”),然后您可以使用此正則表達式

string input = "Hello! world!";

string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);

// result: "Hello! world"

$1 特殊字符包含所有匹配的“world”表達式,用於替換原來的“world!” 表達

暫無
暫無

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

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