Home > Enterprise >  How to split a string into an array of two letter substrings with C#
How to split a string into an array of two letter substrings with C#

Time:09-22

Problem

Given a sample string abcdef, i am trying to split that into an array of two character string elements that should results in ['ab','cd','ef'];

What i tried

I tried to iterate through the string while storing the substring in the current index in an array i declared inside the method, but am getting this output ['ab','bc','cd','de','ef']

Code I used

static string[] mymethod(string str)
{
    string[] r= new string[str.Length];
    for(int i=0; i<str.Length-1; i  )
    {
        r[i]=str.Substring(i,2);
    }
    return r;
}

Any solution to correct that with the code to return the correct output is really welcome, Thanks

CodePudding user response:

If you are using latest version of .NET i.e (.NET 6.0 RC 1), then you can try Chunk() method,

var strChunks = "abcdef".Chunk(2); //[['a', 'b'], ['c', 'd'], ['e', 'f']]

var result = strChunks.Select(x => string.Join('', x)).ToArray(); //["ab", "cd", "ef"]

Note: I am unable to test this on fiddle or my local machine due to latest version of .NET

CodePudding user response:

.net 6 has an IEnumerable.Chunk() method that you can use to do this, as follows:

public static void Main()
{
    string[] result = 
       "abcdef"
       .Chunk(2)
       .Select(chunk => new string(chunk)).ToArray();

    Console.WriteLine(string.Join(", ", result)); // Prints "ab, cd, ef"
}

Before .net 6, you can use MoreLinq.Batch() to do the same thing.

CodePudding user response:

your problem was that you incremented your index by 1 instead of 2 every time

 var res = new List<string>();
 for (int i = 0; i < x.Length - 1; i  = 2)
 {
     res.Add(x.Substring(i, 2));
 }

should work

EDIT: because you ask for a default _ suffix in case of odd characters amount, this should be the change:

  var testString = "odd";
  string workOn = testString.Length % 2 != 0
     ? testString   "_"
     : testString;
  var res = new List<string>();
  for (int i = 0; i < workOn.Length - 1; i  = 2)
  {
      res.Add(workOn.Substring(i, 2));
  }

two notes to notice:

  • in .NET 6 Chunk() is available so you can use this as suggested in other answers
  • this solution might not be the best in case of a very long input so it really depends on what are your inputs and expectations

CodePudding user response:

With linq you can achieve it with the following way:

char[] word = "abcdefg".ToCharArray();
var evenCharacters = word.Where((_, idx) => idx % 2 == 0);
var oddCharacters = word.Where((_, idx) => idx % 2 == 1);
var twoCharacterLongSplits = evenCharacters
    .Zip(oddCharacters)
    .Select((pair) => new char[] { pair.First, pair.Second });

The trick is the following, we create two collections:

  • one where we have only those characters where the original index was even (% 2 == 0)
  • one where we have only those characters where the original index was odd (% 2 == 1)

Then we zip them. So, we create a tuple by taking one item from the even and one item from the odd collection. Then we create a new tuple by taking one item from the even and ...

And last we convert the tuples to arrays to have the desired output format.

CodePudding user response:

You are on the right track but you need to increment by 2 not by one. You also need to check if the array has not ended before taking the second character else you risk running into an index out of bounds exception. Try this code I've written below. I've tried it and it works. Best!

public static List<string> splitstring(string str)
        {
            List<string> result = new List<string>();
            int strlen = str.Length;
            for(int i = 0; i<strlen; i =2)
            {
                string currentstr = str[i].ToString();
                if (i   1 <= strlen-1)
                { currentstr  = str[i   1].ToString(); }
                result.Add(currentstr);
            }
            return result;
        }
  • Related