Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string and print out each word

Tags:

c

I've been given a task where the user inputs a line of text. The program splits each word when it reaches a comma. Once that is done it simply prints out each word on a new line. For example:

Please enter a line of text: Mary,had,a,little,lamb

Mary
had
a
little
lamb

I can't use strtok() because it's not allowed for this task. I can use:

printf(), fprintf(), malloc(), calloc(), realloc(), free(), fgets(), snprintf(), strncpy(), strncat(), strncmp(), strdup(), strlen() and strchr()

So far I've done:

   int i;

   char line[256];
   char *next;

   printf("Enter the string\n");
   fgets(line, 256, stdin);

   char *curr = line;

   while ((next = strchr(curr, ',')) != NULL) {
      curr = next + 1;
   }

   int len = strlen(curr);

   for (i = 0; i < len; i++) {
      printf("%c", curr[i]);
   }

So as of right now if my string was: Mary,had,a,little,lamb

it would only just print out:

lamb

Any advice?

like image 657
Karth Avatar asked Oct 18 '22 16:10

Karth


1 Answers

It is too bad they did not list the most appropriate function for this task: strcspn(). You can get by with strchr() as posted, but there is a problem printing out the result. You can use the %.*s format specifier to print a substring:

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

int main(void) {
    char line[256];

    printf("Enter the string\n");
    if (fgets(line, 256, stdin)) {
        char *curr = line;
        char *next;

        while ((next = strchr(curr, ',')) != NULL) {
            /* found a separator: print the word between curr and next */
            printf("%.*s\n", (int)(next - curr), curr);
            curr = next + 1;
        }
        /* print the last word */
        printf("%s", curr);
    }
    return 0;
}

If you cannot use this somewhat advanced printf feature, you can just modify the string this way:

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

int main(void) {
    char line[256];

    printf("Enter the string\n");
    if (fgets(line, 256, stdin)) {
        char *curr = line;
        char *next;

        while ((next = strchr(curr, ',')) != NULL) {
            /* found a separator: replace it with '\0' */
            *next++ = '\0';
            printf("%s\n", curr);
            curr = next;
        }
        /* print the last word */
        printf("%s", curr);
    }
    return 0;
}

Note also that you could use an even simpler solution, without even a buffer, but using getchar() and putchar() which are not on your list:

#include <stdio.h>

int main(void) {
    int c;

    while ((c = getchar()) != EOF) {
        putchar(c == ',' ? '\n' : c);
        if (c == '\n')
            break;
    }
    return 0;
}

EDIT: If 2 commas next to one another mean a literal comma part of a word, try this:

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

int main(void) {
    char line[256];

    printf("Enter the string\n");
    if (fgets(line, 256, stdin)) {
        char *curr = line;
        char *next;

        while ((next = strchr(curr, ',')) != NULL) {
            /* found a separator: print the word between curr and next */
            if (next[1] == ',') {
                next++;
                printf("%.*s", (int)(next - curr), curr);
            } else {
                printf("%.*s\n", (int)(next - curr), curr);
            }
            curr = next + 1;
        }
        /* print the last word */
        printf("%s", curr);
    }
    return 0;
}

EDIT 2 Given that you are supposed to split the string into an array of pointers, the code is slightly more complicated. The array does not need to be allocated as the number of words is bound by the size of the input buffer:

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

int main(void) {
    char line[256];
    char *array[256];
    int i, n;

    printf("Enter the string\n");
    if (fgets(line, 256, stdin)) {
        char *p = strchr(line, '\n');
        if (p != NULL) {
            *p = '\0';   /* strip the newline if any */
        }
        /* split the line into an array of words */
        n = 0;
        array[n++] = p = line;
        while ((p = strchr(p, ',')) != NULL) {
            *p++ = '\0';
            array[n++] = p;
        }
        /* print the words */
        for (i = 0; i < n; i++) {
            printf("%s\n", array[i]);
        }
    }
    return 0;
}
like image 137
chqrlie Avatar answered Oct 21 '22 08:10

chqrlie