Easiest way to combine 'l','e','t','t','e','r','s'? C# / .NET
I have a string similar to
'l','e','t','t','e','r','s'
or
('l','e','t','t','e','r','s')
I know this should be very easy but i dont know how. I know replacing '
and开发者_如何转开发 ,
with "" is an option since both are illegal characters in the result string but i feel theres a better way to do this.
What is the easist way in C# .NET
That depends what exactly your input-format is.
If you have a string which looks like this, you can either use a chained-Replace:
result = "('l','e','t','t','e','r','s')".Replace("(", String.Empty).Replace("'", String.Empty);
or Regular Expressions to remove everything you did not want (in this case everything that is not a lower or uppercase letter:
result = RegEx.Replace("('l','e','t','t','e','r','s')", "[^a-zA-Z]+", String.Empty);
Even easier is to use one of the Constructors of the String, which accepts Character-Arrays:
result = new String(new Char[] {'l','e','t','t','e','r','s'});
Unless performance is critical, you're probably best of just using simple replacement. The shortest replacement you can write is something along the lines of:
string output = Regex.Replace(input, "\W+", "");
Note that \W
will not remove underscores or numbers. For keeping English letters only, you would use:
string output = Regex.Replace(input, "[^a-zA-Z]+", "");
Well, I think just doing a replace of '/, characters with "" is the best solution, but if you like needlessly complicating things for the sake of premature optimization you could do a regex match on alphabetic characters and then concatenate all the matches together.
Try using RegEx (System.Text.RegularExpressions).
it seems you want to strip out only the alphabetic characters
public static string StripNonAlphabets(string input)
{
Regex reg = new Regex("[^A-Za-z]");
return reg.Replace(str, string.Empty);
}
this method should return what you're looking for
精彩评论