Answers: C Strings Practice


#include <stdio.h>

int main(int argc, char** argv) {
    char one[31];
    char two[11] = "purple";
    char three[11] = "yellow";
    char single;
    int i;
    int count = 0;
    int start, finish;

    // print two and three, capitalize first letter, print again
    printf("two = %s\n", two);
    printf("three = %s\n", three);
    two[0] = 'P';
    three[0] = 'Y';
    printf("two = %s\n", two);
    printf("three = %s\n", three);

    // read into one
    puts("enter a string (30 chars max): ");
    gets(one);
    printf("one = %s\n", one);

    // read a char and count the number of times it's found in one
    puts("enter a char: ");
    scanf("%c", &single);

    for (i = 0 ; one[i] != '\0' ; i++)
        if (one[i] == single)
            count++;

    printf("%c is found in one %d times\n", single, count);

    // print the first word in one

    // skip over leading whitespace if any and save start position
    for (i = 0 ; one[i] == ' ' || one[i] == '\t' ; i++);
    start = i;

    // find end of word
    for ( ; one[i] != ' ' && one[i] != '\t' && one[i] != '\n' ; i++);
    finish = i - 1;

    // print those positions of one
    puts("first word of one: ");
    for (i = start ; i <= finish ; i++)
        printf("%c", one[i]);
    printf("\n");

    return (EXIT_SUCCESS);
}


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2021