【发布时间】:2017-08-06 02:05:23
【问题描述】:
为什么我的变量 nextSpaceIterator 不会更新到 nextSpace 之后的空间索引?
int firstSpace = 0;
int nextSpace = 0;
int nextSpaceIterator = 0;
nextSpace = someInputString.IndexOf((char)ConsoleKey.Spacebar);
//find next space
Console.WriteLine(someInputString.Substring(firstSpace, nextSpace - firstSpace));
// Print word between spaces
firstSpace = nextSpace;
// Starting point for next step is ending point of previous step
nextSpaceIterator = someInputString.IndexOf((char)ConsoleKey.Spacebar, nextSpace);
// Find the next space following the previous one, then repeat.
最初我使用了一个 for 循环,但我已将代码分解为单独的语句以尝试找出问题,但我不能。 一切正常,直到这一点。不应该
nextSpaceIterator = someInputString.IndexOf((char)ConsoleKey.Spacebar, nextSpace);
返回与 nextSpace 不同的值?
【问题讨论】:
-
我认为您必须在
nextspace + 1开始第二次搜索。但不要忘记检查这个新的起始值是否仍在字符串的长度内。 -
另一个问题为您的问题提供了相同的答案stackoverflow.com/a/4578768/3645638