以下程序展示了如何获取字符串中最大长度的连续相同字母,其中应用了指针和字符串操作。
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char *longsubstr(char *str)
{
char *sub;
int i=1,j,jlen;
int n = strlen(str);
int maxj=0,maxjlen=1;
while(i<n){
j = i -1;
jlen = 1;
while(i<n && str[i]==str[i-1]){
i++;
jlen++;
}
if(maxjlen<jlen){
maxjlen = jlen;
maxj = j;
}
i++;
}
printf(“maxj=%d,maxjlen=%d\n”,maxj,maxjlen);
sub = (char * )malloc((n+1)*sizeof(char));
strcpy(sub,str+maxj);
*(sub+maxjlen)=’\0’;
return sub;
}
int main()
{
char str[] = “AAACCCCB”;
char *p = longsubstr(str);
printf(“longest char : %s”,p);
return 1;
}
运行以上程序,最终输出结果如下:
maxj=3,maxjlen=4
longest char : CCCC
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void fun1(char *x){
printf(“1”);
}
void fun2(char *x){
printf(“2”);
}
void fun3(char *x){
printf(“3”);
}
char *longsubstr(char *str)
{
char *sub;
int i=1,j,jlen;
int n = strlen(str);
int maxj=0,maxjlen=1;
while(i<n){
j = i -1;
jlen = 1;
while(i<n && str[i]==str[i-1]){
i++;
jlen++;
}
if(maxjlen<jlen){
maxjlen = jlen;
maxj = j;
}
i++;
}
printf(“maxj=%d,maxjlen=%d\n”,maxj,maxjlen);
sub = (char * )malloc((n+1)*sizeof(char));
strcpy(sub,str+maxj);
*(sub+maxjlen)=’\0’;
return sub;
}
int main()
{
typedef void (F1)(char *c);
char str[] = “AAACCCCB”;
void (a[3])(char * s);
char p = longsubstr(str);
printf(“longest char : %s\n”,p);
void ((pp)[3])(char k);
// pp = &a;
pp = (char)malloc(1sizeof(char *));
*(*pp)= &fun1;
((pp+1))= &fun2;
*(*pp+2)= &fun3;
*(*pp+3)= &fun3;
pp[0]0;
free pp;
F1 *fp3;
fp3 = fun1;
return 1;
}