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
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));