So I am making a small program and I wanted to ask how do I break a string into an array of words? I tried strtok but I what if there is a tab or something like that?
char *S = "This is a cool sentence";
char *words[];
words[0] = "This";
words[1] = "is";
// etc.
Can anyone help?
CodePudding user response:
strtok works just fine even if there are tabs in between. Setting the delimiter(the second argument of strtok) to space(" ") ignores tabs also. For further clarification refer to the below code.
#include<stdio.h>
#include <string.h>
int main() {
// Initialize str with a string with bunch of spaces in between
char str[100] = "Hi! This is a long sentence.";
// Get the first word
char* word = strtok(str, " ");
printf("First word: %s", word); // prints `First word: Hi!`
// Declare an array of string to store each word
char * words[20];
int count = 0;
// Loop through the string to get rest of the words
while (1) {
word = strtok(NULL, " ");
if(!word) break; // breaks out of the loop, if no more word is left
words[count] = word; // Store it in the array
count ;
}
int index = 0;
// Loop through words and print
while(index < count) {
// prints a comma after previous word and then the next word in a new line
printf(",\n%s", words[index]);
index ;
}
return 0;
}
Output (note that there is no space printed between the words and commas) :
First word: Hi!,
This,
is,
a,
long,
sentence.
CodePudding user response:
Certainly making no claims on efficiency/elegance, but this is a possible implementation to split words on all whitespace. This only prints out the words, it does not save them off to an array or elsewhere, I'll leave that as an exercise to you:
#include <stdio.h>
#include <ctype.h>
void printOrSaveWord(char curWord[], size_t curWordIndex)
{
curWord[curWordIndex] = '\0';
if (curWordIndex > 0)
{
printf("%s\n", curWord);
}
}
void separateWords(const char* sentence)
{
char curWord[256] = { 0 };
size_t curWordIndex = 0;
for (size_t i=0; sentence[i]; i )
{
// skip all white space
if (isspace(sentence[i]))
{
// found a space, print out the word. This where you would
// add it to an array or otherwise save it, I'll leave that
// task to you
printOrSaveWord(curWord, curWordIndex);
// reset index
curWordIndex = 0;
}
else
{
curWord[curWordIndex ] = sentence[i];
}
}
// catch the ending case
printOrSaveWord(curWord, curWordIndex);
}