为什么这个C子串方法不起作用?

时间:2013-12-07 07:05:20

标签: c substring

到目前为止我写了这篇文章。 substring(orig,3,3,substr) 鉴于: orig =“onetwothree” 应该做 substr =“two”,但它不是我做错了什么?

void substring(char* source, int start, int length, char* target) {
    int i;
    for(i = 0; i < length; i++) {
        target[i] = source[start + i];
    }
}

2 个答案:

答案 0 :(得分:4)

你忘了将目标字符串归零。

还应该实施一些额外的检查。例如,在复制length个字符之前源字符串结束时会发生什么?

此外,对源指针(const char* source)进行常量限定并使用size_t代替int来表示索引和长度是有意义的。

答案 1 :(得分:0)

您忘记添加空终止字符'\ 0'。

target[length] = '\0';