求字符串连续字符数量

试写一个函数,计算字符串 s中最大连续相同的字符个数。例如,若s 为"aaabbbb",则返回值为4;若s为"abcde",则返回值为1。

函数原型:int max_same_char( char s)

/**
 * file name:ConstanChar_Count.c
 * author   : liaojx2016@126.com
 * date     : 2024-04-08
 * function : Count the max of constant char num
 * note     : None
 * CopyRight (c)   2024  liaojx2016@126.com  Right Reseverd
 *
**/
#include <stdio.h>
#include<string.h>
/**
 *
 * func name      : max_same_char
 * function       : Count max of string's constant char num
 * parameter      : 
 *                      @p :Address pointed to a string
 * Return val      : maxinum of string's constant char num
 * note            : None
 * author          : liaojx2016@126.com
 * date            : 2024-04-08
 * version         : V1.0
 * modify history  : None
 *
**/
int max_same_char( char *p )
{
    int cnt=1;		//记录连续字符数量
    int max=1;		//记录连续字符数量最大值
    //遍历字符串
    while(*p) {
        if(*p==*(p+1)) {
            //此时当前字符与下一个字符相同,字符数量+1
            cnt++;
        }
        else {
            //此时当前字符与下一个字符不相同,比较 cnt与 max,并将较大值赋给 max
            max = (max<cnt)? cnt:max;
            //比较完成之后cnt重新开始计数
            cnt=1;
        }
        p++;	//地址偏移
    }

    return max;
}

int main(int argc, char const *argv[])
{
    char*p="fghfghddddddddfghjdd";
    //scanf("%s",p);
    printf("the string length is %d\n",strlen(p));
    printf("the constant same char num max is %d\n",max_same_char(p));

    return 0;
}

posted @ 2024-05-05 23:58  沉舟道人  阅读(18)  评论(0编辑  收藏  举报