#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 4096
void get_all_sub_str(const char *str, char *result[])
{
int len = strlen(str);
char *temp[MAXLINE];
int num = 0;
for (int head = 0; head < len; head++) {
for (int tail = head; tail < len; tail++) {
temp[num] = (char *)malloc((tail - head + 2) * sizeof(char *));
memset(temp[num], 0x00, tail - head + 2);
strncpy(temp[num], str + head, tail - head + 1 );
result[num] = temp[num];
num++;
}
}
}
int main(int argc, char *argv[])
{
char *result[MAXLINE];
int num = 0;
get_all_sub_str(argv[1], result);
for(; result[num] != NULL; num++) {
printf("result = %s\n", result[num]);
}
return 0;
}
运行结果如下:
cheny@cheny-laptop:~$ gcc get_all_sub_str.c -std\=c99 -o get_all_sub_str
cheny@cheny-laptop:~$ ./get_all_sub_str abcde
result = a
result = ab
result = abc
result = abcd
result = abcde
result = b
result = bc
result = bcd
result = bcde
result = c
result = cd
result = cde
result = d
result = de
result = e
这里面打印出了abcde的所有子串,此处我并不认为ac,ace等不相连的字符串是abcde的子串,另外api里面malloc出来的内存没有free掉,因为free掉了会导致result的结果被清空,不过这个进程会在打印出结果之后就退出掉,malloc的内存会重新归还,但是这个不是一个良好的习惯,但是现在也暂时没有想到好的办法,这题写的比较烂,求各位大大指导一下,谢谢了!