-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

8
  • 2
    How did you do it by hand? Write some code and come back if problem occurs. Commented Jul 29, 2017 at 12:13
  • first, char myString = "the quick brown fox"; --> char *myString = "the quick brown fox"; or char myString[] = "the quick brown fox"; Commented Jul 29, 2017 at 12:14
  • The term you should use to search for is word wrapping. Commented Jul 29, 2017 at 12:15
  • 1
    And possible duplicate of stackoverflow.com/q/15720006/440558 (disclaimer: I wrote an answer with working word-wrap code) Commented Jul 29, 2017 at 12:16
  • Well, "char myString = "the quick brown fox";" isn't valid C. Commented Jul 29, 2017 at 12:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what's your code?
I added more code, in the loop I print word for word and then a newline. You can writer there an if/else newline or space
I'm sorry I can't help you more when you don't post more code and context. What system do you use? The code definitly works...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.