4

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?

2 Answers 2

9

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]*", ""); 
Sign up to request clarification or add additional context in comments.

4 Comments

Are you sure this is faster then Remove and Substring ?
@Smartboy Are you shure there will be any measurable performance benefit from it? TrimStart is easy to read an the overall performance of an method (running in the machine and when read and beeing understood by a dev) might be the best.
@Smartboy: It is the most understandable way and the fastest way to write it. If it is the fastest way at execution time can only be answered by some profiling. However, please optimize this only, if it is a real performance problem that has been verified by a compiler. If you only think it is a performance problem, it most likely isn't.
@Joey: Eh... yes. Now that's embarrassing, I have no idea how that slipped through.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.