【发布时间】:2020-08-06 17:49:57
【问题描述】:
我应该如何在 C++ 中查找 char 数组的长度?我已经尝试了两种方法,但它们都导致数组中的字符数错误。到目前为止,我已经使用了 strlen 和 sizeof 运算符,但无济于事。
void countOccurences(char *str, string word)
{
char *p;
string t = "true";
string f = "false";
vector<string> a;
p = strtok(str, " ");
while (p != NULL)
{
a.push_back(p);
p = strtok(NULL, " ");
}
int c = 0;
for (int i = 0; i < a.size(); i++)
{
if (word == a[i])
{
c++;
}
}
int length = sizeof(str); //This is where I'm having the problem
string result;
cout << length << "\n";
if (length % 2 != 0)
{
if (c % 2 == 0)
{
result = "False";
}
else
{
result = "True";
}
}
else
{
if (c % 2 == 0)
{
result = "True";
}
else
{
result = "False";
}
}
if (strlen(str) != 0)
{
cout << result;
}
}
int boolean()
{
char str[1000];
cin.getline(str, sizeof(str));
string word = "not";
countOccurences(str, word);
return 0;
}
【问题讨论】:
-
字符数组还是 C 字符串?它们是有区别的。如果 C 字符串和
strlen()不起作用,那么您已经搞砸了。如果您丢失了常规数组的大小,那么您已经搞砸了。 -
@sweenish 我说的是 char 数组。
-
strtok修改字符串。您期望获得什么价值?不再存在的原始字符串的大小? -
std::size()可以告诉你数组的大小如果它没有衰减到只是一个指针。顺便提一句;为什么你首先使用 C 风格的数组而不是std::vector或std::array? -
你想在“countOccurences”中做什么?