【问题标题】:I am able to use IndexOf to find a space, why can't I find the next space that way too?我可以使用 IndexOf 找到一个空间,为什么我也不能找到下一个空间呢?
【发布时间】: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 不同的值?

【问题讨论】:

标签: c# indexof


【解决方案1】:

根据代码中的 cmets(在空格之间打印单词),您希望在空格之间获取字符串

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);
}

【讨论】:

    【解决方案2】:
    nextSpace = someInputString.IndexOf((char)ConsoleKey.Spacebar);
    nextSpaceIterator = someInputString.IndexOf((char)ConsoleKey.Spacebar, nextSpace);
    

    nextSpaceIterator 将返回与nextSpace 相同的位置,因为您提供的偏移量从nextSpacesame 索引开始。

    例如:

    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 中的最后一个字符是空格,您将获得索引越界异常。所以你应该经常检查,这可以简单地检查字符串的总长度或计数——哦,别忘了索引从零开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2012-05-27
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多