fcp
fcp

Reputation: 89

How to remove first word from string and keep rest of sentence in C?

I'm trying to manipulate a string by removing the first character or word before a space, and keeping the rest of the sentence.

For example:

char *sentence = {"I am home"};

should become: "am home"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {

    char *sentence = {"I am home"};  
    int space_cnt = 0;
    char *p = sentence;
    char *copy;

    printf("%s\n ", sentence);

        for (int k=0; k<strlen(sentence); k++) {
            if (space_cnt = 0 && ((p=strchr(sentence, ' ')) != NULL)) {
                space_cnt = 1;
            }
            else if (space_cnt = 1) {
                *copy++ = *p;
            }  
        }
    printf("COPY: %s\n", copy);

    return (EXIT_SUCCESS);

}

Current output:

I am home
COPY: 2�

Upvotes: 1

Views: 504

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21532

Since a string is just a pointer to the first element in an array of char terminated by a NULL, you can use pointer arithmetic to get the string after the first word:

char mystring[100] = "Not everybody is going to like this";
char *pstring = mystring;
while(*pstring && *pstring != ' ') 
    pstring++;

puts(pstring);

Output:

 everybody is going to like this

Upvotes: 1

Mureinik
Mureinik

Reputation: 310993

As noted in the comments, you never allocated copy, so you're essentially writing to unallocated space, which will produce an undefined behavior (e..g, on my machine, this code just segfaults).

In fact, you don't even need to copy the string. You can just have copy point to the first character after the space:

char *copy = strchr(sentence, ' ');
if (copy != NULL) {
        copy++;
        printf("COPY %s\n", copy);
}

Upvotes: 1

Related Questions