问题描述
每当有空空间时,我都希望在char中拆分一个数组。
例如,如果给定的char chars [] =“ Test Me”。
返回值应为:
测试
我
#include <stdio.h>
#include "strtok.h"
static char *next = NULL;
char *custom_strtok(char *str)
{
next = custom_strtok(",.-");
while(next != NULL) {
printf ("%s\n",next);
next = custom_strtok(",.-");
}
return NULL;
}
如何在不使用strtok的情况下用空格分割char数组?
解决方法
您将浏览C标准库中C <string.h>
头文件提供的功能列表,并且会发现很多选项。
我写了一些有趣的东西:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct token {
const char *str;
size_t len;
};
struct token next_token(const char *str,const char *sep) {
struct token tok;
/* skip leading separator characters */
str += strspn(str,sep);
tok.str = str;
tok.len = strcspn(str,sep);
return tok;
}
struct token *get_tokens(const char *str,const char *sep) {
size_t len = 0,cap = 8;
struct token *arr = malloc(cap * sizeof *arr);
for (struct token tok = next_token(str,sep); tok.len;
tok = next_token(tok.str + tok.len,sep)) {
arr[len] = tok;
++len;
if (len == cap) {
cap *= 2;
arr = realloc(arr,cap * sizeof *arr);
}
}
arr[len].str = NULL;
arr[len].len = 0;
return arr;
}
int main(int argc,char *argv[]) {
if (argc < 2)
exit(EXIT_FAILURE);
puts("Token array");
struct token *token_arr = get_tokens(argv[1]," \t\n");
for (size_t i = 0; token_arr[i].str; ++i) {
printf("\"%.*s\" ",(int)token_arr[i].len,token_arr[i].str);
}
putchar('\n');
free(token_arr);
puts("Next token loop");
for (struct token tok = next_token(argv[1]," \t\n"); tok.len;
tok = next_token(tok.str + tok.len," \t\n")) {
printf("\"%.*s\" ",(int)tok.len,tok.str);
}
putchar('\n');
return EXIT_SUCCESS;
}