Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I've been using the Split() method to split strings, but this only appears to work if you are splitting a string by a character. Is there a way to split a string, with another string being the split by parameter?

I've tried converting the splitter into a character array, with no luck.

In other words, I'd like to split the string:

THExxQUICKxxBROWNxxFOX

by xx, and return an array with values:

THE, QUICK, BROWN, FOX

What I have tried:

i tried to use linq but never got the desired response.
Posted
Updated 6-Mar-22 19:30pm

In order to split by a string you'll have to use the string array overload.

C#
string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);
 
Share this answer
 
Comments
Maciej Los 7-Mar-22 14:54pm    
5ed!
Tip: i'd use: StringSplitOptions.RemoveEmptyEntries as a second parameter of Split function.
The simpler solution is top just use the string overload version: String.Split Method (System) | Microsoft Docs[^]
C#
string data = "THExxQUICKxxBROWNxxFOX";
foreach (string s in data.Split("xx"))
	{
	Console.WriteLine(s);
	}
 
Share this answer
 
v2
Comments
Maciej Los 7-Mar-22 14:53pm    
Paul, i see 2 errors:
1) no closing bracket in foreach line
2) Split method does not accept single string as a parameter (C1503 - cannot convert string to char[]).
Am i wrong?
OriginalGriff 7-Mar-22 14:58pm    
It was introduced at .NET 6 - check the link.

The missing ")" was a copy'n'paste error - I'll fix it.
Maciej Los 7-Mar-22 15:06pm    
Sorry, but i do not see relevant information or override method...
OriginalGriff 7-Mar-22 15:18pm    
Strange - the link takes me direct to it:
Split(String, StringSplitOptions)
Splits a string into substrings that are based on the provided string separator.

C#

Copy
public string[] Split (string? separator, StringSplitOptions options = System.StringSplitOptions.None);


If you go to the top of the link page, is the .NET version set to ".NET 6"?
Maciej Los 7-Mar-22 16:00pm    
Yes, it's really strange. The link takes me direct to Split function and i see .Net 6.0 version on the top of page, but i do not see overide method with single string parameter :(
I'm not using .Net 6.0, so i can not confirm, but i do believe that there's such of version.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900