剑雨君 发表于 2014-8-5 01:07:03

一个字符串函数的求解,为什么返回值不对。

//编写一个函数,它的原型如:
//        int count_chars(char const *str,char const *chars);
//函数应该在第1个参数中查找,并返回匹配第2个参数所包含的字符的数量。

#include<stdio.h>

int count_chars( char const *str, char const *chars );

int main()
{
        char *str1 = "fa";
        char *str2 = "fuaabfbca";//返回值应该是5
       
        int len;

        len = count_chars( str1, str2 );

        printf( "%d\n", len );

        return 0;
}

int count_chars( char const *str, char const *chars )
{
        int count = 0;


        for( ; *str != '\0'; str++ )
        {
                for( ;*chars != '\0'; chars++ )
                        {
                                if( *str == *chars )
                                        count++;
                        }
        }

        //printf( "%d\n", count );
        return count;
}


戏++ 发表于 2014-8-5 11:05:54

#include<stdio.h>

int count_chars( char const *str, char const *chars );

int main()
{
      char *str1 = "fa";
      char *str2 = "fuaabfbca";//返回值应该是5
      
      int len;
               
      len = count_chars( str1, str2 );
               
      printf( "%d\n", len );
               
      return 0;
}

int count_chars( char const *str, char const *chars )
{
        int count = 0;

        char* p_start1 = str;
        char* p_start2 = chars;
       
       
        for(str=p_start1 ; *str != '\0'; str++ )
        {
                for(chars=p_start2 ;*chars != '\0'; chars++ )
                {
                        if( *str == *chars )
                                count++;
                }
        }
       
        //printf( "%d\n", count );
        return count;
}

剑雨君 发表于 2014-8-5 18:43:21

jianyuling00 发表于 2014-8-5 11:49
你这样在使用循环的时候移动指针,会使循环只能遍历一次,chars循环一次之后指针已经跑到了末尾'\0',所以s ...

就是因为在第二个循环中指针运行到末端,然后第二次回不来开始处是吧。明白了,谢谢。

剑雨君 发表于 2014-8-5 18:43:57

戏++ 发表于 2014-8-5 11:05


明白了,谢谢

网络学习 发表于 2014-8-6 00:33:21

酷暑季节清凉一夏

dsa159245 发表于 2014-8-6 01:35:14

涨姿势了。一开始也没看明白
页: [1]
查看完整版本: 一个字符串函数的求解,为什么返回值不对。