爲什麼我的變量nextSpaceIterator不會更新到nextSpace之後的空間索引?我能夠使用IndexOf查找空間,爲什麼我無法找到下一個空間?
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'開始第二次搜索。但不要忘記檢查這個新的起始值是否仍在字符串的長度內。 – gdir
這個問題提供了與你的問題相同的答案https://stackoverflow.com/a/4578768/3645638 – Svek
可能的重複[在C#中查找大字符串中的子字符串的所有位置](https://stackoverflow.com /問題/ 2641326 /發現-所有位對的一子串-IN-A-大字符串在-C-尖銳) – Fabio