C++中字符串查找操作的两则实例分享

2020-01-06 14:32:13王振洲
  •     还可以使用指针实现。


    在字符串中找出连续最长的数字串
    题目:

    写一个函数,它的原形是 int continumax(char *outputstr,char *intputstr)

    功能:

    在字符串中找出连续最长的数字串,并把这个串的长度返回,

    并把这个最长数字串付给其中一个函数参数 outputstr  所指内存。

    例如:"abcd12345ed125ss123456789" 的首地址传给 intputstr 后,函数将返回 9,

    outputstr  所指的值为 123456789

    题目也比较简单,有一点需要注意

    代码实现(GCC编译通过):

    
    #include "stdio.h"
    #include "stdlib.h"
     
    int continumax(char * outputstr,char * inputstr);
     
    int main(void)
    {
      char *in = "abcd12345ed125dd123456789";
      char *out = (char *)malloc(sizeof(char)*100);
       
      int i = continumax(out,in);
     
      printf("%dn",i);
      printf("%sn",out);
      return 0;
    }
     
    int continumax(char * outputstr, char * inputstr)
    {
      int len,max,i;
      char *p;
     
      len = max = 0;
     
      //若写成while(inputstr != ''),当字符串结尾出现最长数字串则无法处理
      while(1)
      {  
        if(*inputstr >= '0' && *inputstr <= '9')
        {
          len++;
        }
        else
        {
          if(len >max)
          {
            max = len;
            p = inputstr - len;
          }
          len = 0;
        }
        if(*inputstr++ == 0) 
          break;
      }
     
      for(i = 0;i<max;i++)
        *outputstr++ = *p ++;
     
      *outputstr = '';
     
      return max;
    }
    
    


    注:相关教程知识阅读请移步到C++教程频道。