3398 - 考试一 判断字符串中的字符

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

1.输入一个字符串str和一个字符ch,判断str中是否存在该字符;如果存在输出在该字符在串str中出现的次数和位置;

题目输入

hello world!

h

题目输出

1

输入/输出样例

输入格式

hello world!
l

输出格式

2 3 9 
3

C语言解答

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    char str[20];
    char ch ;
    char c;
    int i = 0;
    int count = 0;
    gets(str);
    
    scanf("%c",&ch);

    c = str[i];
    while(c != '\0')
    {
        if(ch == c)
        {
            count++;
            printf("%d ",i);
        }
        c = str[++i];
    }
    printf("\n%d",count);
    return 0;
}

C++解答

#include<iostream>
#include<string>

using namespace std;

int main()
{
	string s;
	char c;
	getline(cin,s);
	cin>>c;
	int sum=0;
	for(int i=0;i<s.length();++i)
	{
		if(s[i]==c)
		{
			cout<<i<<" ";
			sum++;
		}
	}
	cout<<endl;
	cout<<sum;
	return 0;
}