4

Basically, I want to be able to use string.Split(char[]) without actually defining a char array as a separate variable. I know in other languages you could do like string.split([' ', '\n']); or something like that. How would I do this in C#?

3 Answers 3

8

Here's a really nice way to do it:

string[] s = myString.Split("abcdef".ToCharArray());

The above is equivalent to:

string[] s = myString.Split('a', 'b', 'c', 'd', 'e', 'f');
Sign up to request clarification or add additional context in comments.

Comments

1

It's not pretty, but: string.Split(new char[] { ' ', '\n' });

2 Comments

Note that in C# 3 you can make this slightly prettier by eliding the "char". The compiler will work out that new[]{x,y,z} means "new array of the best common type of x, y and z".
Awesome, good to know. I'm guessing this is possible because of the type inference work done for LINQ.
1

you can use this overload:

public String [] Split(params char [] separator)

like this:

yourstring.Split(' ', '\n')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.