Fastest way to remove the leading special characters in string in c#

后端 未结 2 669
甜味超标
甜味超标 2021-01-19 17:37

I am using c# and i have a string like

-Xyz
--Xyz
---Xyz
-Xyz-Abc
--Xyz-Abc

i simply want to remove any leading special character until al

相关标签:
2条回答
  • 2021-01-19 17:43

    I prefer this two methods:

    List<string> strings = new List<string>()
    {
        "-Xyz",
        "--Xyz",
        "---Xyz",
        "-Xyz-Abc",
        "--Xyz-Abc"
    };
    
    foreach (var s in strings)
    {
        string temp;
    
        // String.Trim Method
        char[] charsToTrim = { '*', ' ', '\'', '-', '_' }; // Add more
        temp = s.TrimStart(charsToTrim);
        Console.WriteLine(temp);
    
        // Enumerable.SkipWhile Method
        // Char.IsPunctuation Method (se also Char.IsLetter, Char.IsLetterOrDigit, etc.)
        temp = new String(s.SkipWhile(x => Char.IsPunctuation(x)).ToArray());
        Console.WriteLine(temp);
    }
    
    0 讨论(0)
  • 2021-01-19 18:08

    You could use string.TrimStart and pass in the characters you want to remove:

    var result = yourString.TrimStart('-', '_');
    

    However, this is only a good idea if the number of special characters you want to remove is well-known and small.
    If that's not the case, you can use regular expressions:

    var result = Regex.Replace(yourString, "^[^A-Za-z0-9]*", "");
    
    0 讨论(0)
提交回复
热议问题