Strip first and last character from C string

前端 未结 4 2109
梦毁少年i
梦毁少年i 2020-12-14 16:34

I have a C string that looks like \"Nmy stringP\", where N and P can be any character. How can I edit it into \"my string\" in C?

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 16:57

    Another option, again assuming that "edit" means you want to modify in place:

    void topntail(char *str) {
        size_t len = strlen(str);
        assert(len >= 2); // or whatever you want to do with short strings
        memmove(str, str+1, len-2);
        str[len-2] = 0;
    }
    

    This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.

提交回复
热议问题