tags:

views:

187

answers:

4

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

+10  A: 
result = "('l','e','t','t','e','r','s')".Replace("(", String.Empty).Replace("'", String.Empty;

or

result = RegEx.Replace("('l','e','t','t','e','r','s')", "[^a-zA-Z]+", String.Empty);

or

result = String.Join(String.Empty, new String() {'l','e','t','t','e','r','s'});

or

result = new String(new Char() {'l','e','t','t','e','r','s'});

Bobby

Bobby
I think you have an extra caret in your second option (the RegEx) there.
Sixten Otto
Remove the `^` (or carets will stay in the string) and change the `*` to `+` (or the regex will "match" on every position in the string since it matches zero-length values.)
Blixt
@Sixten Otto, BlixT: Thank you!
Bobby
A: 

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.

Brian Schroth
+1  A: 

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]+", "");
Blixt
About performance: your code should be *pretty* efficient. Don’t underestimate regular expressions.
Konrad Rudolph
True =) Even worse is over-estimating them though ;) It wouldn't be too hard to write some 20 lines of code that will be 10 times faster than the regular expression (although with a pre-compiled regular expression maybe it would only be 3-5 times slower than a custom solution.)
Blixt
A: 

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

Kamal