John
John

Reputation: 3677

How to chop up a string with LINQ

I have a string that needs to be chopped up. I'd like to do this in LINQ. The string can have up to 32 letters. I'd like to collect the parts in a dictionary.

The 1st part needs to have the first 4 letters. 
The 2nd part needs to have the first 5 letters. 
The 3rd part needs to have the first 6 letters. 
etc.

The key of the dictionary is simply a counter. I don't know the length of the string, the min. length is 4. How would I do this createively in LINQ?

Upvotes: 2

Views: 477

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could make it an extension:

public static Dictionary<int, String> Chop(this string str, int minLength)
{
    if (str == null) throw new ArgumentException("str");
    if (str.Length < minLength) throw new ArgumentException("Length of string less than minLength", "minLength");
    var dict = str.TakeWhile((c, index) => index <= str.Length - minLength)
        .Select((c, index) => new { 
            Index = index, 
            Value = str.Substring(0, minLength + index) 
        }).ToDictionary(obj => obj.Index, obj => obj.Value);

    return dict;
}

Call it in this way:

Dictionary<int, String> = "Insert sample string here".Chop(4);

Upvotes: 1

gprasant
gprasant

Reputation: 16023

string word = "abcdefghijklmnopqrstuvwz";

var dict = new Dictionary<int, string>();
for(int i = 0; i < 28;i++)
{
   dict[i] = new string(word.Take(i + 4).ToArray());
}

Upvotes: 0

sloth
sloth

Reputation: 101072

I don't know if I understood correctly what you want to do, but maybe you are looking for something like this:

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = "This is a simple string";
            var dic = Enumerable.Range(4, s.Length-3)
                                .Select((m, i) => new { Key = i, Value = s.Substring(0, m) })
                                .ToDictionary(a=>a.Key,a=>a.Value);
        }
    }
}

Upvotes: 4

Related Questions