2017-08-06 70 views
0

爲什麼我的變量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不同的價值?

+2

我想你必須在'nextspace + 1'開始第二次搜索。但不要忘記檢查這個新的起始值是否仍在字符串的長度內。 – gdir

+0

這個問題提供了與你的問題相同的答案https://stackoverflow.com/a/4578768/3645638 – Svek

+0

可能的重複[在C#中查找大字符串中的子字符串的所有位置](https://stackoverflow.com /問題/ 2641326 /發現-所有位對的一子串-IN-A-大字符串在-C-尖銳) – Fabio

回答

2
nextSpace = someInputString.IndexOf((char)ConsoleKey.Spacebar); 
nextSpaceIterator = someInputString.IndexOf((char)ConsoleKey.Spacebar, nextSpace); 

nextSpaceIterator將返回相同的位置nextSpace,因爲您提供的偏移量開始在nextSpace相同指數。

例如:

string foo = "The quick brown fox"; 

// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 1 8 
// [T][h][e][ ][q][u][i][c][k][ ][b][r][o][w][n][ ][f][o][x] 
//   *     *     *  

// in this example the indexes of spaces are at 3, 9 and 15. 

char characterToMatch = (char)ConsoleKey.Spacebar; 

int first = foo.IndexOf(characterToMatch); // 3 

int invalid = foo.IndexOf(characterToMatch, first); // this will still be 3 

int second = foo.IndexOf(characterToMatch, first + 1); // 9 
int third = foo.IndexOf(characterToMatch, second + 1); // 15 

解。您需要更改偏移向前前進:

nextSpaceIterator = someInputString.IndexOf((char)ConsoleKey.Spacebar, nextSpace+1); 

陷阱。如果string中的最後一個字符是空格,您將獲得索引超出範圍的例外。所以你應該總是檢查一下,可以簡單地檢查字符串的總長度或數量 - 哦,不要忘記索引從零開始。

3

根據您在代碼中的註釋(空格之間打印字),你想獲得

Console.WriteLine(someInputString.Substring(firstSpace, nextSpace - firstSpace));` 
// Print word between spaces 

空間之間的字符串如果是這樣,那麼使用String.Split Method

var words = someInputString.Split((char)ConsoleKey.Spacebar); 

var firstWord = words[0]; 
var secondWord = words[1]; // If you sure that there at least two words 

// or loop the result 
foreach (var word in words) 
{ 
    Console.WriteLine(word); 
} 
相關問題