How to cut part of a string in c?

后端 未结 6 1844
面向向阳花
面向向阳花 2021-02-14 19:22

I\'m trying to figure out how to cut part of a string in C. For example you have this character string \"The dog died because a car hit him while it was crossing the road\" how

6条回答
  •  一生所求
    2021-02-14 20:00

    The following function cuts a given range out of a char buffer. The range is identified by startng index and length. A negative length may be specified to indicate the range from the starting index to the end of the string.

    /*
     *      Remove given section from string. Negative len means remove
     *      everything up to the end.
     */
    int str_cut(char *str, int begin, int len)
    {
        int l = strlen(str);
    
        if (len < 0) len = l - begin;
        if (begin + len > l) len = l - begin;
        memmove(str + begin, str + begin + len, l - len + 1);
    
        return len;
    }
    

    The char range is cut out by moving everything after the range including the terminating '\0' to the starting index with memmove, thereby overwriting the range. The text in the range is lost.

    Note that you need to pass a char buffer whose contents can be changed. Don't pass string literals that are stored in read-only memory.

提交回复
热议问题