-4

I am new in C programming, my training uses Redhat, Unix and I already spent my day searching for a solution. I know manipulating a string in C is difficult for me as beginner.

How can I split the string into individual words so I can loop through them?. Or convert a string into char array to be able to access individual elements.

char myString[] = "the quick brown fox";

To be exact i want to print each word of the said string into a fixed column and whenever the the string reached that number of column it will go to new line and print the sequence without splitting the word.

eg. print it within 12 columns only w/out splitting the word:

the quick 
brown fox

and not:

the quick br
own fox

..TIA

Andy
  • 49,085
  • 60
  • 166
  • 233
lambda
  • 990
  • 1
  • 10
  • 29

1 Answers1

1

Your problem can be split into two parts, part A you need to split the sentence into words and part B you need to print a maximum of x characters per line.

Part A - Split the String

Take a look at the strok function. You can use space as the delimiter.

#include <stdio.h>
#include <string.h>
// You need this line if you use Visual Studio
#pragma warning(disable : 4996)

int main()
{
    char myString[] = "the quick brown fox";
    char* newString;
    newString= strtok(myString, " ,.-");
    while (newString!= NULL)
    {
        printf("%s\n", newString);
        newString= strtok(NULL, " ,.-");
    }

    return 0;
}

Output:

the
quick
brown
fox

Part B

Now you want to print the words and insert a newline when you reach the max columns 12 in your example. You need to check the length of every extracted word, you can use strlen for that. When the string is to long you insert a newline...

Hope it helped, if something is unclear leave a comment.

clfaster
  • 1,450
  • 19
  • 26