day04

67 阅读1分钟

写一个程序,接受一个由字母、数字和空格组成的字符串和一个目标字符。然后输出该字符串中该目标字符出现的次数。不区分大小写。

思路:

  1. 使用一个数组来输入一个字符串
  2. 输入一个字符
  3. 朴素进行比较。进行统计。
  4. 时间复杂度为o(n)

难点:

  1. 字符串的输入
  2. char类型数组的输入

具体实现:

#include <stdio.h>
#include <stdlib.h>

int count_x(char *str,char ch)
{
    int i=0;
    int count=0;
    while(str[i]!='\0')
    {
        if(str[i]==ch||str[i]+'0'==ch||str[i]-'0'==ch)
        {
            count++;
        }
        i++;
    }
    return count;
}
int main()
{
    char str[1000];
    scanf("%s",str);
    char c;
    while((c=getchar())!='\n');
    char ch;
    scanf("%c",&ch);

    printf("%d",count_x(str,ch));

    return 0;
}

具体问题:

char类型数组中不能有空字符

需要清空一些数据

因此使用string类型比较合适 cin输入字符串不能有空格

- still have some proble 
- kongge can not solve

getline(cin,str)

#include <iostream>

using namespace std;

int main()
{
    string s;
    getline(cin,s);

    char ch;
    cin>>ch;
    int coun=0;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]==ch)
            coun++;
    }

    printf("%d",coun);
    return 0;
}