C# How to split string based on 2 parameters? - c#

I have three string called This_is string1 and This is string2 There_is string3
How to split these 3 strings after "This_", "This " "There_) in one condition? basically, i want to split based on first "_" or " " in a string in one condition.

The answer is simple, you can use the String.Split method, specifying the multiple delimiters (in your case the underscore and whitespace):
str.Split(new char[]{'_',' '})
LinQPad result:
If you want to split only the first part, you can use the 2nd overload of String.Split:
str.Split(new char[]{'_',' '}, 2);
and this is the result in LinQPad:

So you want to split only the first part? You can use the overload of String.Split that allows to specify the count and multiple delimiters:
str.Split(new[]{' ', '_'}, 2);
So on the first string you get: "This" + "is string1", similar on the others.

Related

Better way to split a string "a_b_c_d.1.2.3.4"

what is the best ways to split sting "aaa_bx_cd_de.1000.20.3.40" to "aaa_bx_cd_de" and "1000.20.3.40" in C#.net application
mainstring="aaa_bx_cd_de.1000.20.3.40"
str1="aaa_bx_cd_de"
str2="1000.20.3.40"
You can use an overload of String.Split[1] that takes as a second argument the number of substrings you want returned (essentially the number of splits plus 1).
string mainstring = "a_b_c_d.1.2.3.4";
string[] parts = string.Split(new [] {'.'}, 2);
// parts[0] will be "a_b_c_d"
// parts[1] will be "1.2.3.4"
[1] https://msdn.microsoft.com/en-us/library/c1bs0eda(v=vs.110).aspx

How can I use String.Split with a String delimiter?

I have string like so:
"ABCDEF--Split--GHIKLMO--Split--PQRSTUVWXYZ"
what I am trying to do is split this string with --Split-- being the delimiter, I have obviously tried the following:
var array = item.split('--Split--');
but I get this error:
Too many characters in character literal
Is there away to do this?
The problem with your above code is that you are trying to pass in a string as a char instead of using the correct overload:
item.Split(new []{"--Split--"}, StringSplitOptions.None)
MSDN Documentation
You're using the string.Split that uses CHAR as parameter. See that single quote are used to create char type in C#.
You have to use the overload that receives an string array as parameter.
item.split(new string[]{"--Split--"},StringSplitOptions.RemoveEmptyEntries);
The first parameter is an array of strings that you want to split.
The second parameter, the StringSplitOptions has two possible values:
None (will split also empty values), the example below will give you an string array with three elements. The first will be "This is an string test", second wil lbe "I will split by ", and third will be "":
var test = "This is an string test, I will split by ,";
var splittedStrings = test.Split(",", StringSplitOptions.None);
RemoveEmptyEntries, this will remove the empty entries of splitted string. If you take the example above using the RemoveEmptyEntries you will have an array with only two values: "This is an string test" and "I will split by ". The empty string at final will be cutted of.

Confusing error when splitting a string

I have this line of code:
string[] ids = Request.Params["service"].Split(",");
the values in Request.Params["service"] are: "1,2"
Why am I getting:
Error 1 The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'char[]'
This makes no sense to me....
The error happens on everything to the right of the equal sign
You need to pass a character (System.Char), not a string:
string[] ids = Request.Params["service"].Split(',');
There is no overload to String.Split that takes a params string[] or a single string, which is what would be required to make your code work.
If you wanted to split with a string (or multiple strings), you would need to use a string[] and specify splitting options:
string[] ids = Request.Params["service"].Split(new[]{","}, StringSplitOptions.None);
You have to use the overload with the params Char[]:
string[] ids = Request.Params["service"].Split(',');
As others said on here your provided (",") the double quote denotes a string and the Split function accepts a Character array or char[]. Use (',') , the single quote denotes a character. You can also pass along StringSplitOptions which if you happen to get empty values in your string[] it requires a char[] to be passed along with it, illustrated below.
string splitMe = "test1,test2,";
string[] splitted1 = splitMe.Split(',');
string[] splitted2 = splitMe.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
//Will be length 3 due to extra comma
MessageBox.Show(splitted1.Length.ToString());
//Will be length 2, Removed the empty entry since there was nothing after the comma
MessageBox.Show(splitted2.Length.ToString());
In the line
Request.Params["service"].Split(",");
You're splitting by "," instead of ','
The .Split() method takes an array of characters, not a string

how to split a string by another string?

I have a string in following format
"TestString 1 <^> TestString 2 <^> Test String3
Which i want to split by "<^>" string.
Using following statement it gives the output i want
"TestString 1 <^> TestString 2 <^> Test String3"
.Split("<^>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
But if my string contains "<" , ">" or "^" anywhere in the text then above split statement will consider that as well
Any idea how to split only for "<^>" string ?
By using ToCharArray you are saying "split on any of these characters"; to split on the sequence "<^>" you must use the overload that accepts a string[]:
string[] parts = yourValue.Split(new string[]{"<^>"}, StringSplitOptions.None);
Or in C# 3:
string[] parts = yourValue.Split(new[]{"<^>"}, StringSplitOptions.None);
Edit: As others pointed already out: String.Split has a good overload for your usecase. The answer below is still correct (as in working), but - not the way to go.
That's because this string.Split overload takes an array of separator chars. Each of them splits the string.
You want: Regex.Split
Regex regex = new Regex(#"<\^>");
string[] substrings = regex.Split("TestString 1 <^> TestString 2 <^> Test String3");
And - a sidenote:
"<^>".ToCharArray()
is really just a fancy way to say
new[]{'<', '^', '>'}
Try another overloaded Split method:
public string[] Split(
string[] separator,
StringSplitOptions options
)
So in you case it may looks like:
var result =
yourString.Split(new string[] {"<^>"},StringSplitOptions.RemoveEmptyEntries);
Hope, this helps.

String splitting produces different results than expected

it returns not what i expected.
i expected something like:
ab
cab
ab
what am i doing wrong?
don't do .ToCharArray()
it will split \r then \n
that why you have empty value
something like this should work
var aa = ("a" & Environment.NewLine & "b" & Environment.NewLine & "c").Split(New String[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
Since you are splitting on "\r" and "n", String.Split extracts the empty string from "\r\n".
Take a look at StringSplitOptions.RemoveEmptyEntries or use new String[] { "\r\n" } instead of "\r\n".ToCharArray().
You just splitting the string using \r or \n as delimiters, not the \r\n together.
Environment.NewLine is probably the way to go but if not this works
var ab = "a\r\nb\r\nc";
var abs = ab.Split(new[]{"\r\n"}, StringSplitOptions.None);
This option also works,
string [] b = Regex.Split(abc, "\r\n");
My understanding is that the string char sequence you provide to the Split method is a list of delimiter characters, not a single delimiter madeof several characters.
In your case, Split consider the '\r' and '\n' characters as delimiters. So when it encounters the '\r\n' sequence, it returns the string between those 2 delimiters, an empty string.

Categories