qfedu-c-level/day11/homework/h8.c

78 lines
1.7 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 设计函数 char (*tok(char *s, const char *delim))[100] 实现s按给定的分隔符分隔出所有的内容并返回分隔之后的二维数组指针。
// 示例:
// char s[] = "Hello,World,How,Are,You";
// const char delim[] = ",";
// char(*tokens)[100] = tok(s, delim);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char (*tok(char *s, const char *delim))[100]
{
// 计算分隔符的长度
size_t delim_len = strlen(delim);
// 计算字符串中分隔符的个数
int count = 1;
char *p = s;
while (*p != '\0')
{
if (strncmp(p, delim, delim_len) == 0)
{
count++;
p += delim_len; // 跳过分隔符
}
else
{
p++;
}
}
// 分配存储结果的二维数组
char(*tokens)[100] = malloc(count * sizeof(*tokens));
// 分隔字符串
int i = 0;
p = s;
char *token_start = p;
while (*p != '\0')
{
if (strncmp(p, delim, delim_len) == 0)
{
strncpy(tokens[i], token_start, p - token_start);
tokens[i][p - token_start] = '\0';
i++;
p += delim_len; // 跳过分隔符
token_start = p;
}
else
{
p++;
}
}
// 处理最后一个分隔符后的部分
strncpy(tokens[i], token_start, p - token_start);
tokens[i][p - token_start] = '\0';
return tokens;
}
int main()
{
char s[] = "Hello,World,How,Are,You";
const char delim[] = ",";
char(*tokens)[100] = tok(s, delim);
// 打印分隔后的结果
for (int i = 0; tokens[i][0] != '\0'; i++)
{
printf("%s\n", tokens[i]);
}
// 释放内存
free(tokens);
return 0;
}