简体   繁体   English

如何将字符串拆分为包含前一个字符的两个字符的字符串数组?

[英]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.我有这个词,我想将它拆分为 arrays,并在每次拆分迭代中取最后一个字符。

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

Output result: Output 结果:

[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 :如果您想要 LINQ 解决方案,您可以使用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.这使用Skip作为偏移量将word中的每个字符与自身压缩,并且仍然具有与显式循环一样的O(n)复杂度。

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 : 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.我认为以下代码实现了您想要的 output。 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或者使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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