Home > Back-end >  How to separate 2 letters from each other when they are entered in without spaces?
How to separate 2 letters from each other when they are entered in without spaces?

Time:11-28

I have a task to write some code that will put 2 letters that are entered in as, for example, "ab" using one ReadLine() and then separate them into strings c1 and c2 respectively, so that c1=a, and c2=b. How can I accomplish this?

CodePudding user response:

If I'm not mistaken you can use:

String mystring = Console.ReadLine(); // "ab"

Char c1 = mystring[0];
Char c2 = mystring[1];

CodePudding user response:

In modern C# we have a feature called ranges

var input = Console.ReadLine();

var s1 = input[0..1];
var s2 = input[1..2];

This is slightly different to Airodene's answer, which uses a single number indexer on the string to retrieve the character at the position. Ranges are used to cut a string up smaller strings. You can use any number pair that refers to positions within the string , omitting a number infers the start/end and you can use ^ before a number to mean "from the end" instead of the start

input[^3..] //get between 3-from-end and end 
input[..^3] //get between start and 3-from-end
  • Related