returns 来自给定索引的子字符串的函数

Function that returns a sub char string from given Indices

实现函数:

char* subCstring(char * inStr, int start_index, int end_index)

将 char 数组作为输入,它是一个 c 字符串,returns 是 start_index 和 end_index 之间对应字符的 c 字符串。

我们可以蚕食输入字符串,过早地将其清空并返回字符串内部的指针。

char* subCstring(char * inStr, int start_index, int end_index)
{
    inStr[end_index] = '[=10=]'; // end_index + 1 if the end index is inclusive
    return &inStr[start_index];
}

请注意,这不会检查以确保开始小于结束并且两者都在输入字符串的范围内。您可能需要添加此类检查。

如果你不能蚕食你的输入字符串,即是只读的,那么你可以为函数中的结果分配内存,不要忘记 free 之后:

char* subCstring(char * inStr, int start_index, int end_index)
{
    char *out = (char *) malloc(end_index - start_index + 2); // need '2' here to keep '[=10=]'
    strncpy(out, inStr + start_index, end_index-start_index+1);
    return out;
}

如果你的函数的结果在第二次调用函数之前被消耗,你也可以对结果使用静态分配。

char* subCstring(char * inStr, int start_index, int end_index)
{
    static char out [256];
    strncpy(out, min(255, inStr + start_index, end_index-start_index+1));
    return out;
}

您还可以在参数中为结果传递分配的内存。

或者您可以使用 'c++' std::string 以更优雅的方式进行。

 char* subCstring(char * inStr, int start_index, int end_index) {
    char * sub = new char[end_index];
    sub[end_index] = '[=10=]';
    strncpy(sub, inStr+start_index, end_index);
    return sub;


}