Strip first and last character from C string

前端 未结 4 2116
梦毁少年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 17:12

    The most efficient way:

    //Note destroys the original string by removing it's last char
    // Do not pass in a string literal.
    char * getAllButFirstAndLast(char *input)
    {
      int len = strlen(input); 
      if(len > 0)
        input++;//Go past the first char
      if(len > 1)
        input[len - 2] = '\0';//Replace the last char with a null termination
      return input;
    }
    
    
    //...
    //Call it like so
    char str[512];
    strcpy(str, "hello world");
    char *pMod = getAllButFirstAndLast(str);
    

    The safest way:

    void getAllButFirstAndLast(const char *input, char *output)
    {
      int len = strlen(input);
      if(len > 0)
        strcpy(output, ++input);
      if(len > 1)
        output[len - 2] = '\0';
    }
    
    
    //...
    //Call it like so
    char mod[512];
    getAllButFirstAndLast("hello world", mod);
    

    The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.

提交回复
热议问题