如何在C语言中实现类似Python split(' ')的字符串分割功能?
在C语言中实现类似Python split(' ')的字符串分割函数
如果你只需要按空格分割单词(忽略连续空格,和Python的str.split()行为一致),用strtok()是最简单的方案,它专门用来分割字符串,会自动处理连续的分隔符:
#include <stdio.h> #include <string.h> int main() { // 注意:strtok会修改原字符串,所以这里要用字符数组而不是字符串常量 char input_str[] = "I have 3 spaces in this sentence"; char* word_array[10]; // 预设最多存储10个单词,可按需调整 int word_count = 0; // 第一次调用传入原始字符串和分隔符(空格) char* current_word = strtok(input_str, " "); while (current_word != NULL) { word_array[word_count++] = current_word; // 后续调用传入NULL,继续分割剩余的字符串 current_word = strtok(NULL, " "); } // 打印结果 for (int i = 0; i < word_count; i++) { printf("Word %d: %s\n", i + 1, word_array[i]); } return 0; }
注意事项:
strtok()会直接修改原字符串(把分隔符替换成'\0'),如果原字符串不能被修改,需要先复制一份再处理,比如用strdup()或者strcpy()到新的字符数组中。- 这个方案会把连续的多个空格视为单个分隔符,如果你需要严格匹配Python
str.split(' ')的行为(比如连续空格会生成空字符串元素),就得手动实现分割逻辑:
#include <stdio.h> #include <stdlib.h> #include <string.h> // 按单个空格分割字符串,返回存储单词的数组,count参数输出单词总数 char** split_exact_space(const char* input, int* count) { int str_len = strlen(input); *count = 0; // 先统计分割后的元素数量(包括空字符串) for (int i = 0; i <= str_len; i++) { if (i == str_len || input[i] == ' ') { (*count)++; } } // 分配存储单词数组的内存 char** result = malloc((*count) * sizeof(char*)); if (!result) { *count = 0; return NULL; } int start_idx = 0; int idx = 0; for (int i = 0; i <= str_len; i++) { if (i == str_len || input[i] == ' ') { int word_len = i - start_idx; // 分配单个单词的内存,加1用于存储结束符'\0' result[idx] = malloc((word_len + 1) * sizeof(char)); if (!result[idx]) { // 内存分配失败,释放已分配的资源 for (int j = 0; j < idx; j++) { free(result[j]); } free(result); *count = 0; return NULL; } // 复制子字符串并手动添加结束符 strncpy(result[idx], input + start_idx, word_len); result[idx][word_len] = '\0'; idx++; start_idx = i + 1; } } return result; } int main() { const char* test_str = "Hello world this "; int count; char** words = split_exact_space(test_str, &count); if (words) { for (int i = 0; i < count; i++) { printf("Element %d: '%s'\n", i + 1, words[i]); free(words[i]); // 释放单个单词的内存 } free(words); // 释放数组本身的内存 } return 0; }
这个手动实现的函数会和Python split(' ')完全一致,比如输入"a b"会得到三个元素:"a"、""、"b"。
内容的提问来源于stack exchange,提问作者Tilcsa220
相关产品推荐
相关产品推荐

