2017-08-06 69 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); 
} 
相关问题