从C字符串中获取奇怪的字符串长度

Getting weird string lengths from C string

本文关键字:字符串 获取      更新时间:2023-10-16

我正试图从c字符串中提取单词,然后与2d数组中的单词进行比较,并计算匹配单词的数量。我注意到有些字符串长度不是我所期望的,这可能就是numMatches不正确的原因,但我不确定为什么我得到的字符串长度不匹配。我哪里错了?

#include <iostream>
using namespace std;
#include <string.h>

int main ()
{
char str[] ="bob amy ted susan";
char * pch;
pch = strtok (str," ");
char arr[4][10] = {"bob", "amy", "susan", "ted"};
int numMatches = 0;
int i = 0;
while (pch != NULL)
{
cout<< pch <<endl;
cout << strlen(arr[i]) << endl;
if (strcmp(pch,arr[i])==0){
numMatches++;
}
pch = strtok (NULL, " ");
i++;

}
cout << arr[2] << endl;
cout << numMatches << endl;
return 0;
}
Output I'm getting...
bob
3
amy
3
ted
5
susan
3
Total Matches : 2
Output I'm expecting...
bob
3
amy
3
ted
3
susan
5
Total Matches : 4

一步一步地完成代码,然后"执行";它在你的脑海中/纸上:

First iteration:
i == 0
pch == "bob"
arr[i] == arr[0] == "bob"
strlen("bob") == 3
numMatches increased to 1
Second iteration:
i == 1
pch == "amy"
arr[i] == arr[1] == "amy"
strlen("amy") == 3
numMatches increased to 2
Third iteration:
i == 2
pch == "ted"
arr[i] == arr[2] == "susan"
strlen("susan") == 5
numMatches NOT increased, stays at 2
Forth iteration:
i == 3
pch == "susan"
arr[i] == arr[3] == "ted"
strlen("ted") == 3
numMatches NOT increased, stays at 2
Done, pch == NULL

正如您所看到的,您正在将令牌(pch(与arr的一个值进行比较。您可能想要第二个循环,它在arr[i]上循环i的所有可能值。理想情况下,您应该将这个循环放入其自己的函数中,名称建议isInArr(或matches或…很大程度上取决于它最终应该变成什么:(


更多建议:

  • using namespace std;不要
  • #include <string.h>这是针对C的,当在C++中包含C标头时,请使用#include <cstring>
  • 如果这段代码的目的不是学习C字符串和strtok,那么最好使用更多的C++惯用代码,例如std::stringstream(PaulMcKenzie的例子,以防注释丢失(