C++ 计算字符数组中的字符数,包括空格直到空字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3778928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count number of chars in char array including spaces until null char
提问by Zac
I'm trying to count the number of chars in a char array including the space until the end of the string.
我正在尝试计算字符数组中的字符数,包括直到字符串末尾的空格。
The following compiles but doesn't return the correct value, I'm trying to use pointer arithmetic to interate through my array.
以下编译但没有返回正确的值,我正在尝试使用指针算术来交互我的数组。
int numberOfCharsInArray(char* array) {
int numberOfChars = 0;
while (array++ != 'int numberOfCharsInArray(char* array){
int numberOfChars = 0;
while (*array++){
numberOfChars++;
}
return numberOfChars;
}
') {
numberOfChars++;
}
return numberOfChars;
}
Many thanks.
非常感谢。
Obviously I'm trying to get the equivalent of length() from cstring but using a simple char array.
显然,我试图从 cstring 中获得与 length() 等效的值,但使用了一个简单的 char 数组。
Of course if my original array wasn't null terminated this could cause a very big value to return (I guess).
当然,如果我的原始数组不是空终止,这可能会导致返回一个非常大的值(我猜)。
回答by codaddict
To access the char pointer by the pointer you need to dereferencethe pointer. Currently you are
comparing array
( an address) with
'\0'
要通过指针访问字符指针,您需要取消对指针的引用。目前您正在比较array
(一个地址)与
'\0'
You can fix your code like:
您可以修复您的代码,如:
int numberOfCharsInArray(char* array) {
return strlen(array);
}
The cstring function you are imitating is strlen
not length
.
您正在模仿的 cstring 函数strlen
不是length
.
EDIT:
编辑:
To know how the condition in the while works you can see this thread.
要了解 while 中的条件如何工作,您可以查看此线程。
回答by John Dibling
Perhaps I'm missing something, but why not just:
也许我错过了一些东西,但为什么不只是:
int numberOfCharsInArray(char* array) {
return std::string(array).length();
}
...or even:
...甚至:
int numberOfCharsInArray(char* array){
int numberOfChars = 0;
while (*array != 'static const size_t maxExpectedChars = 4 * 1024; // Max chars expected, e.g. 4K
size_t numberOfCharsInArray( char * array) {
if( !array ) { return 0; } // A non-existing string has `0` length
size_t charsSoFar = 0;
while ( *array ) {
charsSoFar += 1;
if( charsSoFar == maxExpectedChars ) { break; } // Stop runaway loop
++array;
}
return charsSoFar;
}
'){
numberOfChars++; array++;
}
return numberOfChars;
}
回答by gspr
When you write array++ != '\0'
you check if the memory addressarray
is '\0'. Try this instead:
写入array++ != '\0'
时检查内存地址array
是否为“\0”。试试这个:
Edit: Oops, codaddict was faster and his code more elegant.
编辑:糟糕,codacci 速度更快,他的代码更优雅。