abdou93
abdou93

Reputation: 175

How can I split string into array of string that take two characters with including the previous last character?

I have this word and I would like to split it into arrays with taking the last previous character in every iteration of split .

string word = "HelloWorld!";
string[] mystringarray = word.Select(x => new string(x, 2)).ToArray();
Console.WriteLine(mystringarray);

Output result :

[HH,ee,ll,oo,WW,oo,rr,ll,dd,!!]

Expected result :

[He,el,ll,lo,ow,wo,or,rl,ld]

How can I achieve that?

Upvotes: 2

Views: 945

Answers (3)

persian-theme
persian-theme

Reputation: 6638

I think the following code implements the output you want. Its algorithm is :

(0, 1),
(1, 2),
(2, 3),
......

 string[] mystringarray = word.
         Select((x,i) => 
                i == 0 || i + 1 == word.Length ? x.ToString() : x + word.Substring(i,1))
        .ToArray();

Or use Enumerable.Range

string[] mystringarray2 = Enumerable.Range(0, word.Length).
      Select(i => i == 0 || i + 1 == word.Length ? word[i].ToString() : word[i] + word.Substring(i,1))
     .ToArray();

Upvotes: -1

Johnathan Barclay
Johnathan Barclay

Reputation: 20363

If you want a LINQ solution, you could use Zip:

string[] mystringarray = word
    .Zip(word.Skip(1), (a, b) => $"{a}{b}")
    .ToArray();

This zips each character in word with itself, using Skip as an offset, and still has O(n) complexity as with an explicit loop.

Upvotes: 5

Orion
Orion

Reputation: 822

string word = "HelloWorld!";
List<string> mystringarray = new();

for (int i = 1; i < word.Length; i++)
{
    mystringarray.Add(word.Substring(i-1, 2));
}

Contents of mystringarray:

List<string>(10) { "He", "el", "ll", "lo", "oW", "Wo", "or", "rl", "ld", "d!" }

Note the exclamation mark which I'm not sure you wanted to include.

Upvotes: 3

Related Questions