一个字符串中多个元素用空格分开 用C语言写一个函数提取字符串中各个元素
时间: 2023-02-06 07:02:18 浏览: 74
在 C 语言中,可以使用字符串函数 `strtok` 来分割字符串。
下面是一个示例函数,它接受一个字符串和一个字符串分隔符,并返回使用该分隔符分割后的字符串数组:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_TOKENS 100
char **split(char *str, char *delim) {
char **tokens = malloc(MAX_TOKENS * sizeof(char *));
char *token = strtok(str, delim);
int i = 0;
while (token != NULL) {
tokens[i++] = token;
token = strtok(NULL, delim);
}
tokens[i] = NULL;
return tokens;
}
int main() {
char str[] = "one two three four";
char **tokens = split(str, " ");
for (int i = 0; tokens[i] != NULL; i++) {
printf("%s\n", tokens[i]);
}
free(tokens);
return 0;
}
```
输出结果:
```
one
two
three
four
```
注意,这个示例函数使用了 `malloc` 函数来动态分配内存,因此调用完函数后需要使用 `free` 函数释放内存。