如何继续循环字符串并返回给定索引的字符?

时间:2016-11-10 17:01:09

标签: c# string

pm-suspend

现在输出应为char output = string myinput = "ABC"; int inputLoopIndex = 5;

我试过

B

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

2 个答案:

答案 0 :(得分:1)

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

你想使用modulo(%)运算符,它可以有效地循环(它得到余数)。 Read more about it on Wikipedia

答案 1 :(得分:0)

您需要处理溢出数组长度的迭代器

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