Search code examples
cstringwords

Delete first word from string on C


I have a function that receive two char array (resource and result) and change them. the result will be only the first word and resource for everything that it was before, except the first word. The first word is written to the result, but in the resource removes some spaces...

void selectFirstWord(char *src, char* res) {
int i = 1;

while(*src != ' ' && *src != 0) {
   *(res++) = *(src++); //посимвольное копирование из src в res
   i++;
}

while(*src != 0) {
    *(src++) = *(src+i);
}

*res = 0;
}

Solution

  • You can keep a copy of the original src

    void selectFirstWord(char *src, char* res) {
    
        char *copy = src;                  // keep copy
    
        while(*src != ' ' && *src != 0) {
            *res++ = *src++;
        }
        *res = 0; // "close" res
    
        while(*src == ' ') src++; // eat spaces after the word
    
        // Copy the rest of src to `copy`
        do {
            *copy++ = *src;   
        } while(*src++ != 0);
    }
    

    Differences with your code

    • copy keeps copy of src
    • after res gets first word of src, eat following spaces in src
    • then copy the remaining part of src to copy (which points to the original src)

    There is also a solution using indexes. src[i], but here we just follow src being incremented from start to bottom.