有没有更好的方法来编写这个功能?

时间:2011-09-12 19:26:37

标签: c string

这是一个插入字符串函数,

void ins( char * T, size_t ip, char * P)
{
    char temp1[100], temp2[100];

    strncpy(temp1,T,ip);
    strcpy(temp2, &T[ip]);

    strcat(&T[ip], P);
    strcat(&T[sizeof(temp1) + sizeof(P) - 2], temp2);
}

有没有更好的方法来编写这个函数?

1 个答案:

答案 0 :(得分:1)

我需要添加一个额外的参数maxlen:可以写入的str的最大大小。我还将返回类型修改为有用的东西。

size_t do_insert(char *str, size_t maxlen, size_t where, char *ins)
{
    size_t len_str, len_ins;

    /* these could be arguments, too,
    ** if these are already known by the caller.
    */
    len_str = strlen(str);
    len_ins = strlen(ins);

    /* not enough space: return */
    if (len_str + len_ins >= maxlen)
        return len_str + len_ins;

    /* I don't know what should happen if the place to insert
    ** is beyond the length of str
    ** [ there also is a corner case lurking here if where == len_str]
    */
    if (where > len_str)
        return ???;

    /* make place for the insert by shifting str up.
    ** we move one byte extra: the nul character.
    */
    memmove( str + where + len_ins, str + where, len_ins + 1);

    /* put the insert where it belongs */
    memcpy ( str + where, ins, len_ins );

    /* return the length of the new string */
    return len_str + len_ins;
}

注意:未经测试。