Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!