Strip first and last character from C string

前端 未结 4 2064
梦毁少年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:53

    To "remove" the 1st character point to the second character:

    char mystr[] = "Nmy stringP";
    char *p = mystr;
    p++; /* 'N' is not in `p` */
    

    To remove the last character replace it with a '\0'.

    p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 17:05

    Further to @pmg's answer, note that you can do both operations in one statement:

    char mystr[] = "Nmy stringP";
    char *p = mystr;
    p++[strlen(p)-1] = 0;
    

    This will likely work as expected but behavior is undefined in C standard.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题