如何将字符串放入 C 中的"words"数组中?



所以我正在制作一个小程序,我想问我如何将字符串分解为单词数组?我试过strtok,但是如果有tab之类的呢?

char *S = "This  is     a cool sentence";
char *words[];
words[0] = "This";
words[1] = "is";
// etc.

有人能帮忙吗?

strtok工作很好,即使有标签之间。设置分隔符(strtok的第二个参数)space(";")也忽略所有连续的空格。如需进一步说明,请参阅以下代码。

编辑:正如@Chris Dodd正确地提到的,您应该将t添加到分隔符strtok(str, " t")中以忽略制表符。


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

int main() {
// Initialize str with a string with bunch of spaces and tabs in between
char str[100] = "Hi!     This   is a      long        sentence.";

// Get the first word
char* word = strtok(str, " t");
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, " t");
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;
}

(注意单词和逗号之间没有空格):

First word: Hi!,
This,
is,
a,
long,
sentence.

当然不要求效率/优雅,但这是在所有空白上分割单词的可能实现。这只打印出单词,它不会将它们保存到数组或其他地方,我将把它留给您作为练习:

#include <stdio.h>
#include <ctype.h>
void printOrSaveWord(char curWord[], size_t curWordIndex)
{
curWord[curWordIndex] = '';
if (curWordIndex > 0)
{
printf("%sn", 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);
}

示范

最新更新