简体   繁体   中英

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?

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.

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM