Q L*_*Liu 3 c++ string pointers
如何返回指向char数组中间某些内容的指针?
// Returns a pointer to the first occurrence of the given character in the
// given string.
const char* strchr(const char* string, char charToFind) {
for (int i = 0; i < strlen(string); i++) {
if (string[i] == charToFind) {
return string[i]; // <== THIS IS WRONG, How do I fix this?
}
}
return '\0';
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做
return &string[i];
Run Code Online (Sandbox Code Playgroud)
或者像这样:
return string+i;
Run Code Online (Sandbox Code Playgroud)
这是同一件事.
返回'\0',一个char等于零的常量,在逻辑上是不正确的:你应该返回0一个NULL指针,或者如果你想返回一个空C字符串,你可以返回一个指向本地静态空字符串的指针,如下所示:
const char* strchr(const char* string, char charToFind) {
for (int i = 0; i < strlen(string); i++) {
...
}
// Not found - return an empty string:
static const char *empty = "";
return empty;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4697 次 |
| 最近记录: |