简体   繁体   中英

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

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 alphabet comes , Note: Special characters in the middle of string will remain same . What is the fastest way to do this?

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]*", "");

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM