C++语言问题在线求解

编写函数replace(),将用户输入的字符串中的字符t(T)都替换成e(E),并返回替换字符的个数。

#include <iostream>
using namespace std;
int replace(char *p)
{
    int i=0;
    int cnt = 0;
    while(p[i])
    {
        if(p[i]== 't')
        {
            cnt++;
            p[i]='e';
        }
        else if(p[i]=='T')
        {
            cnt++;
            p[i]='E';
        }
        i++;
    }
    return cnt;
}
int main()
{
    char buf[100];
    gets(buf);
    cout << "替换个数:"<<replace(buf)<<endl;
    cout << "替换后的字符串:"<<buf<<endl;
    return 0;
}

把数组遍历一下,检查字符是否t或T,根据大小写对应替换。统计个数

#include <iostream>
using namespace std;
int replace(char *s)
{
      int count = 0;
      int i=0;
      while(s[i] != 0)
      {
          if(s[i] == 't')
          {
               s[i] = 'e';
               count++;
          }
          else if(s[i] == 'T')
          {
               s[i] = 'E';
               count++;
          }
      }
      return count;
}
int main()
{
      char s[100];
      gets(s);
      int count = replace(s);
      cout<<s<<endl;
      cout<<"共替换"<<count<<"次";
      return 0;
}