Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split string with two characters C#

i need to split a string with 2 characters. There are 2 cases. For example "abcdef" = "{ab, cd, ef}". OR {abcde} = {"ab, cd, e_"}. If the last pair contains 1 symbol, add ‘_’. This is what i tried with first case

    public static string[] Split(string str)
    {
        var symbols  = str.ToCharArray();
        string[] result_arr = new string[str.Length];

        if(symbols.Length % 2 == 0)
        {
            for(int i = 0; i<symbols.Length-1; i += 2)
            {
                result_arr[i] = symbols[i].ToString() + symbols[i+1].ToString(); 
            }
        }
        
        return result_arr;
    }

The output is

ab

cd

ef

instead of

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ab
cd
ef

>Solution :

using Enumerable.Range and LINQ

var input = "abcdef";
var result = Enumerable.Range(0, input.Length / 2).Select(x => input.Substring(x * 2, 2));
Console.WriteLine(string.Join(", ", result));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading