Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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?

like image 349
Smartboy Avatar asked Jan 14 '23 20:01

Smartboy


1 Answers

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]*", "");
like image 63
Daniel Hilgarth Avatar answered Feb 06 '23 09:02

Daniel Hilgarth