[Solved] C programming: Delete string before first space [closed]


This code should work for you. It makes use of the fact, that str is a pointer to the first character of the string.

char *str = "Hello world";
/*
 * Uncomment if `str` could be `NULL`:
 *
 * if (str == NULL) {
 *     fprintf(stderr, "Error: invalid string\n");
 *     exit(EXIT_FAILURE);
 * }
 */
while (*str != ' ' && *str != '\0') {
    ++str;
}
if (*str == ' ')
    ++str;

If you are not very familiar with pointers, this is a similar approach that might be easier to understand.

char *str = "Hello world";
/*
 * Uncomment if `str` could be `NULL`:
 *
 * if (str == NULL) {
 *     fprintf(stderr, "Error: invalid string\n");
 *     exit(EXIT_FAILURE);
 * }
 */
int i = 0;
while (str[i] != ' ' && str[i] != '\0') {
    ++i;
}
if (str[0] == ' ')
    str = &str[i + 1];

9

solved C programming: Delete string before first space [closed]