user1740381
user1740381

Reputation: 2199

How to split string in 2 word string set in c#

I have a string in c#. I want to split that string into 2 words string sets like:

string str = "Split handles splitting upon string and character delimiters."

Output should be:

1: "Split handles"
2: "splitting upon"
3: "string and"
4: "character delimiters."

What should be the best method to do this?

Here is what i have tried yet:

    private List<string> Spilt(string text)
    {
        List<string> bunch = new List<string>();
        int block = 15;
        string[] words = text.Split(' ');
        int length = words.Length;
        int remain = 0;

        while(remain < length)
        {
            bunch.Add(string.Join(" ", words.Take(block)));
            remain += block;
        }

        return bunch;
    }

Upvotes: 1

Views: 1648

Answers (2)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13755

Try this

        string str = "Split handles splitting upon string and character delimiters.";
        var strnew = str.Split(' ');
        var strRes = string.Empty;
        int j = 1; 
        for (int i = 0; i < strnew.Length; i=i+2)
        {
            strRes += j.ToString()+": " + @"""" + strnew[i] + " " + strnew[i+1] + @"""" +"\n" ;
            j++; 
        }
        Console.Write(strRes); 
        // print strRes

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

The simplest approach would be to split at each space, and then "re-join" the pairs back, like this:

var pairs = str.Split(' ')
    .Select((s,i) => new {s, i})
    .GroupBy(n => n.i / 2)
    .Select(g => string.Join(" ", g.Select(p=>p.s)))
    .ToList();

Demo on ideone.

Upvotes: 5

Related Questions