Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda