user979331
user979331

Reputation: 11961

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?

Upvotes: 1

Views: 631

Answers (2)

brenton
brenton

Reputation: 558

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

Upvotes: 4

Ricardo Silva
Ricardo Silva

Reputation: 1384

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.

Upvotes: 0

Related Questions