字符串从长到短求子串

proghua 2011-10-11 10:10:51
假设有字符串“abcdefgh”,如何先求长度为8的子串,然后求长度为7的子串,依次类推,最后求长度为1的子串,中间如果找到满足条件的可以退出
...全文
206 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
embedlinuxgame 2011-10-11
  • 打赏
  • 举报
回复
++

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
int begin, end, step;
char str[] = "abcdefghijklmn";
int len = strlen(str);
char *substr = (char*)malloc(sizeof(str));

begin = 0;
end = len-1;
step = len-1;
while(1)
{
if (step == 0)
{
break;
}
memset(substr, 0, sizeof(str));
memcpy(substr, str+begin, step);

printf("%s\n", substr);
if (begin + step < end)
{
++begin;
continue;
}
if (begin + step == end)
{
begin = 0;
--step;
}
}

return 0;
}
embedlinuxgame 2011-10-11
  • 打赏
  • 举报
回复
一个循环可以搞定的程序,你写了三重循环,难道你没研究过算法复杂度????
haofang666777 2011-10-11
  • 打赏
  • 举报
回复
++[Quote=引用 2 楼 zhao4zhong1 的回复:]
仅供参考

C/C++ code
#include <stdio.h>
#include <string.h>
char *a="abcde";
int L,i,j,k;
void main() {
L=strlen(a);
for (i=1;i<=L;i++) {
for (j=0;j<=L-i;j++) {
for ……
[/Quote]
赵4老师 2011-10-11
  • 打赏
  • 举报
回复
仅供参考
#include <stdio.h>
#include <string.h>
char *a="abcde";
int L,i,j,k;
void main() {
L=strlen(a);
for (i=1;i<=L;i++) {
for (j=0;j<=L-i;j++) {
for (k=j;k<j+i;k++) {
printf("%c",a[k]);
}
printf("\n");
}
}
}
测试NULL 2011-10-11
  • 打赏
  • 举报
回复
做出来了,如果有问题加我Q : 506341588
注释去掉就是找到满足条件退出的功能


#include<stdio.h>
#include<string.h>
#include<malloc.h>

int main()
{
int begin, end, step;
char str[] = "abcdefghijklmn";
int len = strlen(str);
char *substr = (char*)malloc(sizeof(str));

begin = 0;
end = len-1;
step = len-1;
while(1)
{
if (step == 0)
{
break;
}
memset(substr, 0, sizeof(str));

memcpy(substr, str+begin, step);

/*找到满足条件退出*/
/*
if (strcmp(substr, "cdefg") == 0)
{
break;
}
*/

printf("%s\n", substr);

if (begin + step < end)
{
++begin;
continue;
}

if (begin + step == end)
{
begin = 0;
--step;
}
}

return 0;
}
hlyces 2011-10-11
  • 打赏
  • 举报
回复
算法复杂度是一样的吧
赵4老师 2011-10-11
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 embedlinuxgame 的回复:]
一个循环可以搞定的程序,你写了三重循环,难道你没研究过算法复杂度????
[/Quote]
我只研究代码对应多少条汇编指令和使用了多少个字节的内存单元。
测试NULL 2011-10-11
  • 打赏
  • 举报
回复
恩,可以用string带的函数来做
七擒关羽 2011-10-11
  • 打赏
  • 举报
回复
感觉LZ的都没有理解题意:
假设有字符串“abcdefgh”,如何先求长度为8的子串,然后求长度为7的子串,依次类推,最后求长度为1的子串,中间如果找到满足条件的可以退出
1、8子串 abcdefgh
2、7子串 abcdefg bcdefgh
3、6子串 abcdef bcdefg cdefgh
。。。
8、1子串 a b c d e f g h

这个string带的函数就可以操作吧
guoshuxia 2011-10-11
  • 打赏
  • 举报
回复
好难啊,不懂。。
hondely 2011-10-11
  • 打赏
  • 举报
回复
so easy!

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧