注册 登录
编程论坛 C++教室

c++题目,求大神解答,解释一下。

风雨123 发布于 2013-02-26 17:00, 642 次点击
统计每个字母的个数
  输入一行字母,统计每个字母的个数,并输出字母及相应个数,
 字母和数字用一个空格隔开。
例如:
标准输入:
abf aaa bf
标准输出:
a 4 b 2 f 2
12 回复
#2
azzbcc2013-02-26 17:07
额,介个,代码呢?
#3
风雨1232013-02-26 17:16
帮我讲一下思路,一些代码
#4
风雨1232013-02-26 17:19
#include <iostream>
#include <string>
using namespace std;
int main()
{
  char s[80];
  int i,n,m=0,k;
  cin.getline(s,80);
  n=strlen(s);
  for(i=0;i<n;i++)
  {
      for(k=i+1;k<n;k++)
      {
          if(i==k)continue;
          else if(s[i]==s[k])
             m++;
      }
      if(i==0)
      cout<<s[i]<<" "<<m;
      else if(i>0)
          cout<<" "<<s[i]<<" "<<m;
      m=0;
  }
  cout<<endl;
  return 0;
}
这是错的。
#5
Susake2013-02-26 17:27
。。。。
#6
azzbcc2013-02-26 17:33
表示看不懂你的内循环,i<k恒成立的吧

我的思路就是加一个result数组,result[0]表示 ‘a’的个数......

先将result数组置0,然后 result[ s[i] - 'a' ]++ 就可以,最后遍历result数组,非 0就输出
#7
songjie3332013-02-26 19:27
程序代码:
#include "stdafx.h"
#include
#include
#include
#include
using std::string;
using std::cin;
using std::cout;
using std::endl;
int _tmain(int argc, _TCHAR* argv[])
{
    string s;
    //cin>>s;
    getline(cin,s);
    int len=s.length();
    if(!s.empty())
    {
       int count[100];
       for(int i=0;i<=len-1;i++)
           count[i]=1;
       for(int j=1;j<=len-1;j++)
       {       for(int i=0;i<J;I++)
                 if(s[j]==s[i])
                   {  count[i]++;
                      count[j]--;
                        break;}
        }
     for(int i=0;i<LEN;I++)
     if(count[i]>0&&isalpha(s[i]))
         cout<<S[I]<<" "<<COUNT[I]<<ENDL;
     }
    system("pause");
    return 0;
}
ok了
#8
azzbcc2013-02-26 21:36
程序代码:
#include <stdio.h>
#include <string.h>

int main()
{
    char s[80];
    int i = 0, len, result[26] = {0};
    for (gets(s), len = strlen(s); i < len; ++i)
    {
        ++result[ s[i] - 'a' ];
    }
    for    (i = 0; i < 26; ++i)
    {
        if (result[i])
            printf("%c %d ", i + 'a', result[i]);
    }
    puts("");
    return 0;
}


代码问题较多,理解下思路就好

[ 本帖最后由 azzbcc 于 2013-2-26 23:03 编辑 ]
#9
额外覆盖2013-02-26 22:28
我就不多嘴了,楼上的算法挺好的,学习了
#10
sam0312013-02-26 22:31
楼上这哥们。。。
这个是C哦
都是高手
#11
日出地平线2013-02-27 10:15
求救我的C++啊
#12
dhybc2013-02-27 10:31
挺简洁的
#13
风雨1232013-02-27 14:02
谢谢各位!!!
1