题目:
写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)
功能:在字符串中找出连续最长的数字串,并把这个串的长度返回,
并把这个最长数字串付给其中一个函数参数outputstr所指内存。
例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回9,
outputstr所指的值为123456789
一开始写的代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char intputstr[100],outputstr[100];
int continumax(char *outputstr,char *intputstr);
int main()
{
int result;
while (printf("Please input a string: "),scanf("%s",intputstr)!=EOF)
{
result=continumax(outputstr,intputstr);
printf("The result is : %d \n\n",result);
}
return 0;
}
int continumax(char *outputstr,char *intputstr)
{
int i,tempIndex,len,maxNum=0; //tempIndex为下标的副本,len为输入字符串的长度,maxNum为长度的最大值
for (len=0;intputstr[len]!=0;len++);//求输入字符串长度
for (i=0;i<len;i++)
{
if (isdigit(intputstr[i]))
{
tempIndex=i;
for (i++;i<len&&isdigit(intputstr[i]);i++);
if (maxNum<i-tempIndex+1)
{
maxNum=i-tempIndex;
outputstr=&intputstr[tempIndex];
}
}
}
outputstr[maxNum]=0;
printf("%s ",outputstr);
return maxNum;
}
但是这个程序不怎么好。
1、输入的字符串不能有空格;
2、输入字符串的长度还要求出来;
3、求得的最长数字字符串必须在函数中输出,因为outputstr指针的地址可能会改变!!
所以改进一下:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int continumax(char *outputstr,char *intputstr);
int main()
{
int result;
char intputstr[100],outputstr[100];
while (printf("Please input a string: "),fgets(intputstr,sizeof(intputstr),stdin)!=NULL) //改为fgets输入字符串
{
result=continumax(outputstr,intputstr);
printf("The result is : %d %s\n\n",result,outputstr);
}
return 0;
}
int continumax(char *outputstr,char *intputstr)
{
int maxNum=0,count=0,i;//count计数
char *head=NULL;//head为最长字符串的首地址
while (*intputstr!=NULL)
{
if (isdigit(*intputstr))
{
count++;
}
else
{
if (count>maxNum)
{
maxNum=count;
head=intputstr-maxNum;
}
count=0;
}
intputstr++;
}
outputstr[maxNum]=0; //不能忘
for (i=0;i<maxNum;i++)
{
*outputstr=*head; //不改变outputstr地址
outputstr++;
head++;
}
return maxNum;
}