How to cut part of a string in c?

后端 未结 6 2034
面向向阳花
面向向阳花 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 19:45

    You can use something similar to Python's [n:m] cut operator via a simple code but involves dynamic allocation and also preserve the original string that is an input.

    char* cutoff(const char* str, int from , int to)
    {
        if (from >= to)
            return  NULL;
    
        char* cut = calloc(sizeof(char), (to - from) + 1);
        char* begin = cut;
        if (!cut)
            return  NULL;
    
        const char* fromit = str+from;
        const char* toit = str+to;
        (void)toit;
        memcpy(cut, fromit, to);
        return begin;
    }
    

提交回复
热议问题