Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何返回指向char数组中间的某个指针?_C++_String_Pointers - Fatal编程技术网

C++ 如何返回指向char数组中间的某个指针?

C++ 如何返回指向char数组中间的某个指针?,c++,string,pointers,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] == char

如何返回指向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';
}
//返回一个指针,指向给定字符在
//给定字符串。
常量字符*strchr(常量字符*string,字符chartofId){
for(int i=0;i返回字符串[i];//如果您有一个指向字符串的指针,则向其中添加N将返回指向同一字符串部分的指针,从第N个字符开始(对于基于零的计数)

另外,最好为指向空字符串的指针设置一个常量

static const char* EMPTY_STRING = '\0';

const char* strchr(const char* string, char charToFind) {
    for (int i = 0; i < strlen(string); i++) {
        if (string[i] == charToFind) {
            return string+i; 
        }
    }
    return EMPTY_STRING;
}
static const char*空字符串='\0';
常量字符*strchr(常量字符*string,字符chartofId){
for(int i=0;i
你可以这样做

return &string[i];
或者像这样:

return string+i;
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;
}
是一样的

返回
'\0'
,一个
char
常量等于零,在逻辑上是不正确的:对于
NULL
指针,应该返回
0
,或者如果希望返回空C字符串,可以返回指向本地静态空字符串的指针,如下所示:

return string+i;
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;
}
const char*strchr(const char*string,char charToFind){
for(int i=0;i
正如@dasblinkenlight提到的,
&string[i]
string+i
都用于返回字符串中间的指针。正如@Oliver Matthews所述,如果找不到字符,则应返回NULL。可能超出了原始查询的范围,但出于性能原因,您可能希望避免调用
strlen()
,扫描时只需检查字符串的结尾,如下所示:

const char* strchr(const char* string, char charToFind) {
    for (int i = 0; string[i]; i++) {    // Or you could say string[i] != '\0'
        if (string[i] == charToFind) {
            return string + i; 
        }
    }
    return NULL;
}

故障路径应该返回
null
而不是
\0
-从技术上讲,您是在返回字符值0,并对
char*
@oliver:What是
null
?您的意思是
null
nullptr
空字符串
对于空指针来说是一个误导性的名称。或者您是这样做的吗您想用
而不是零来初始化它吗?