Smartboy
Smartboy

Reputation: 1006

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?

Upvotes: 4

Views: 6697

Answers (2)

kletnoe
kletnoe

Reputation: 399

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

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

Upvotes: 9

Related Questions