(程序员面试题)字符串处理之获取字符串的所有子串

#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的内存会重新归还,但是这个不是一个良好的习惯,但是现在也暂时没有想到好的办法,这题写的比较烂,求各位大大指导一下,谢谢了!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值