user7098023
user7098023

Reputation:

Print word by word (new lines) using String

I've tried to print a string of words one by one (individual) but I'm stuck over here... that otherwise prints the whole string four times but that's not the logic I intended.

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

int main()
{
    char str[] = "Hello! A_word and Another_word";
    unsigned int count = 0;
    unsigned int str_size = strlen(str);

    do {
        while(str[count++] != 32) {
            // more codes needed here I think to manipulate one word
        }
        // print one word and proceed
        printf("%s\n", str);
    } while(count < str_size);

    return(0);
}

The output should be:

Hello!
A_word
and
Another_word

Upvotes: 0

Views: 179

Answers (2)

Ilario Pierbattista
Ilario Pierbattista

Reputation: 3265

Basically you need to convert spaces (' ') in newlines ('\n').

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

int main()
{
    char str[] = "Hello! A_word and Another_word";
    unsigned int str_size = strlen(str);

    for(int i = 0; i < str_size; i++) {
        if(str[i] == ' ') printf("\n");
        else printf("%c", str[i]);
    }

    return 0;
}

You can also make the code more simple, following the assumption that a string is an array of chars terminating with the '\0' char.

#include <stdio.h>

int main() {
    char str[] = "Hello! A_word and Another_word";

    for(int i = 0; str[i] != '\0'; i++) {
        if(str[i] == ' ') printf("\n");
        else printf("%c", str[i]);
    }

    return 0;
}

Upvotes: 2

Overflow 404
Overflow 404

Reputation: 492

I suggest you to use strtok_r(), here is your code:

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

int main(void)
{
    char str[] = "Hello! A_word and Another_word";
    char *token;
    char *saveptr = str;
    while (1) {
        token = strtok_r(saveptr, " ", &saveptr);
        if (token == NULL) {
            break;
        }
        printf("%s\n", token);
    }
    return(0);
}

Upvotes: 0

Related Questions