Coder Perfect

How do I use a string delimiter to split a string? [duplicate]

Problem

I have the following string:

My name is Marco and I'm from Italy

I’d like to break it into two halves, with Marco as the delimiter, and so I should obtain an array with

I’m not sure how I’m going to do it in C#.

I tried with:

.Split("is Marco and")

However, it simply requires a single character.

Asked by markzzz

Solution #1

string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);

If your delimiter is a single character (for example,,), you can reduce it to (notice the single quotes):

string[] tokens = str.Split(',');

Answered by juergen d

Solution #2

.Split(new string[] { "is Marco and" }, StringSplitOptions.None)

Take a look at the places around “is Marco and.” Do you want the spaces to be included in your final product, or do you want them to be removed? It’s probable that you’ll wish to utilize the separators “is Marco” and “is Marco”…

Answered by Anders Marzi Tornblad

Solution #3

You’re breaking a string into several substrings. Instead of String, I’d use regular expressions. Split. The latter is mostly used for tokenizing text.

For example:

var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");

Answered by Huusom

Solution #4

Instead, use this function.

string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);

Answered by DanTheMan

Solution #5

You may retrieve a location for the string using the IndexOf method, then split it using that point and the length of the search string.

Regular expressions can also be used. This was the result of a basic Google search.

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {
        Console.WriteLine(line);
    }
  }
}

Answered by Patrick

Post is based on https://stackoverflow.com/questions/8928601/how-can-i-split-a-string-with-a-string-delimiter