从C字符串中获取奇怪的字符串长度
Getting weird string lengths from C string
我正试图从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的例子,以防注释丢失(
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取