1、写一个函数,它的原形是int continumax(char *outputstr,char *intputstr)
功能:
在字符串中找出连续最长的数字串,并把这个串的长度返回,并把这个最长数字串付给其中一个函数参数outputstr所指内存。例如:"abcd12345ed125ss123456789"的首地址传给intputstr后,函数将返回
9,outputstr所指的值为123456789。
#include <stdio.h> #include <stdlib.h> #include <string.h> int FindMax_NumStr(char *outputstr,char *inputstr) { char *in = inputstr,*out = outputstr,*temp; char *final; int count = 0; int maxlen = 0; int i; while(*in!='\0') { if(*in > 47 && *in < 58) { for(temp = in;*in> 47 && *in <58;in++) count++; } else in++; if(maxlen < count) { maxlen = count; count = 0; final = temp; } } for(i =0;i<maxlen;i++) { *out = *final; out++; final++; } *out = '\0'; return maxlen; } void main(void) { char input[]="abc123def123456eec123456789dd"; char output[50] = {0}; int maxlen; maxlen = FindMax_NumStr(output,input); printf("the str %s\n",output); printf("the maxlen is %d\n",maxlen); }
2.、用指针的方法,将字符串“ABCD1234efgh”前后对调显示
#include <stdio.h> #include <string.h> int main() { char str[]="ABCD123efgh"; int length = strlen(str); char *p1= str; char *p2 = str+length -1; while(p1<p2) { char c = *p1; *p1 = *p2; *p2 = c; ++p1; --p2; } printf("str now is %s\n",str); return 1; } | 3.给定字符串A和B,输出A和B中的最大公共子串。比如A="aocdfe" B="pmcdfa" 则输出"cdf"
#include <stdio.h> #include <stdlib.h> #include <string.h> char *commanstring(char shortstring[],char longstring[]) { int i,j; char *substring = malloc(256); if(strstr(longstring,shortstring)!=NULL) return shortstring; for(i=strlen(shortstring)-1;i>0;i--) { for(j=0;j<=strlen(shortstring)-i;j++) { memcpy(substring,&shortstring[j],i); substring[i]='\0'; if(strstr(longstring,substring)!=NULL) return substring; } } return NULL; } void main(void) { char *str1 = "aocdfe"; char *str2 = "pmcdfa"; char *comman = NULL; if(strlen(str1)>strlen(str2)) comman= commanstring(str2,str1); else comman = commanstring(str1,str2); printf("the longest comman string is:%s\n",comman); } | |