How to read words in a string using C language?

In the C language, one common method is to use string handling functions to read words from a string.

  1. splitting a string into smaller parts
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello world, how are you?";
    char *token = strtok(str, " "); // 使用空格作为分隔符

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " "); // 继续获取下一个单词
    }

    return 0;
}
  1. Loop through the string to check each character individually to determine if it is a delimiter for words.
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello world, how are you?";
    int len = strlen(str);
    int i, j, start = 0;

    for (i = 0; i <= len; i++) {
        // 判断是否为分隔符,包括空格、逗号、句号等常见符号
        if (str[i] == ' ' || str[i] == ',' || str[i] == '.' || str[i] == '\0') {
            // 输出从 start 到当前位置的字符,即一个单词
            for (j = start; j < i; j++) {
                printf("%c", str[j]);
            }
            printf("\n");
            // 更新下一个单词的起始位置
            start = i + 1;
        }
    }

    return 0;
}

Here are two common methods for extracting words from a string, you can choose the one that best fits your needs.

bannerAds