Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Parsing strings (C) (1) Prompt the user for a string that contains two strings s

ID: 3888788 • Letter: P

Question

Parsing strings (C)

(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)

Examples of strings that can be accepted:

Jill, Allen

Jill , Allen

Jill,Allen

Ex:


(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. (2 pts)

Ex:


(3) Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings. (2 pts)

Ex:


(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)

Explanation / Answer

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

#define BUFFER_SIZE 1000

void trim(char *str) {
    int i, begin = 0;
    int end = strlen(str) - 1;

    while (isspace((unsigned char) str[begin])) {
      begin++;
    }

    while ((end >= begin) && isspace((unsigned char) str[end])) {
      end--;
    }

    for (i = begin; i <= end; i++) {
      str[i - begin] = str[i];
    }
    str[i - begin] = '';
}

int main() {
    char input[BUFFER_SIZE];
    int i =0;

    while (1) {
        printf("Enter input string : ");
        fgets(input, BUFSIZ, stdin);
        if (strcmp(input, "q ") == 0) {
          break;
        }

        for (i=0; i<strlen(input); i++) {
          if (input[i] == ',') {
            char *first_word, *second_word;
            char *search = ",";
            first_word = strtok(input,search);
            second_word = strtok(NULL,search);
            trim(first_word);
            trim(second_word);
            printf("First Word : %s ", first_word);
            printf("Second Word : %s ", second_word);
            exit(0);
          }
        }

        printf("Error: No comma in string. ");
    }

}