如何解决?

yslcuk 2007-02-15 06:12:49
标准C中有一个字符串如:551+553+667:670+722
当有:时应取成(667,668,669,670)
最后得出以下列如:
551
553
667
668
669
670
722
如何解决?
...全文
245 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fosjos 2007-02-15
  • 打赏
  • 举报
回复
纠正:int a[20]={0};
a[j] = -1;//作为结束符

提醒一下WingForce 的bug:
551+553+667:670
yslcuk 2007-02-15
  • 打赏
  • 举报
回复
ok
fosjos 2007-02-15
  • 打赏
  • 举报
回复
char str[] = "551+553+667:670+722";
int a[20];
int i=0,j=0;
int flag=0; //标识':'
for(;;i++){
if(str[i]>='0'&&str[i]<='9')
a[j] = a[j]*10 + (str[i]-'0');
else{
if(flag){
flag = 0;
int max = a[j];
for(;a[j-1]<max;j++)
a[j] = a[j-1]+1; //print
}else
j++;

if(str[i]=='+' || str[i]==':'){
a[j] = 0; //print
flag = (str[i]==':');
}else
break;
}
}
a[++j] = -1; //作为结束符
WingForce 2007-02-15
  • 打赏
  • 举报
回复
。。。
一直没有看懂,那再改下好了。。。其实很简单

#include <stdio.h>
#include <stdlib.h>
#define is_number( ch ) ( (ch) >= '0' && (ch) <='9' )
#define is_connector( ch ) ( (ch) == ':' )
char* buf = "551+553+667:670+722:750+780";

int main(int argc, char *argv[])
{
char* p = buf;
int pre = 0, out = 0;
/* ...p指向目的buf */
while( *p != '\0' )
{
if( is_number( *p ) )
{
out = out * 10 + *p - '0';
}
else if( is_connector( *p ) )
{
pre = out;
out = 0;
}
else
{
if( pre != 0 )
{
while( pre++ < out ) printf( "%d\n", pre );
pre = 0;
}
else
printf( "%d\n", out );

out = 0;
}
p++;
}

if( out != 0 )
printf( "%d\n", out );

system("PAUSE");
return 0;

}
yslcuk 2007-02-15
  • 打赏
  • 举报
回复
楼上的
我的意思是有冒号时就连续输出,如667:670,
就输出成
667
668
669
670
谢谢
WingForce 2007-02-15
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#define is_number( ch ) ( (ch) >= '0' && (ch) <='9' )
char* buf = "551+553+667:670+722";

int main(int argc, char *argv[])
{
char* p = buf;
int out = 0;
/* ...p指向目的buf */
while( *p != '\0' )
{
if( is_number( *p ) )
{
putchar( *p );
}
else
{
putchar( '\n' );
}
p++;
}


system("PAUSE");
return 0;

}
yslcuk 2007-02-15
  • 打赏
  • 举报
回复
楼上的,不对呀
WingForce 2007-02-15
  • 打赏
  • 举报
回复
#define is_number( ch ) ( (ch) >= '0' && (ch) <='9' )

char* p;
int out = 0;
/* ...p指向目的buf */
while( *p != '\0' )
{
if( is_number( *p ) )
out += (*p *10)
else
{
printf( "%d\n", out );
out = 0;
}
p++;
}
hmichaelchen 2007-02-15
  • 打赏
  • 举报
回复
从字符串开始分析,分三个分支分析字符串,数字一个,+一个,:一个,遇到:以后,将:以前的数字+1,然后和:以后的数字比较,相等了就往后分析,否则继续+,回家了在网吧的,写程序不方便,不然就给你一段代码了。
其实你只要把连续的数字分析出来就可以了,算是写一个字符串到数字的转变函数而已,和简单,其他的符号只是一个分析标志。

69,381

社区成员

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

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