Neo Neo - 22 days ago 8
C# Question

how to continues loop through string and return character of given index?

string myinput = "ABC";
int inputLoopIndex = 5;


now output should be char output =
B


I tried like

string myinput = "ABC";
char mycharachter;
for (int i = 0; i <= inputLoopIndex ; i++)
{
mycharachter = myinput[i];
}


Error -
Index out of bound

Answer
string myinput = "ABC";
char mycharachter;
for (int i = 0; i <= 5; i++)
{
    mycharachter = mystring[i % mystring.Length];
}

You want to use the modulo (%) operator, which can be used effectively to loop round (it gets the remainder). Read more about it on Wikipedia.

Comments