1389 - 统计字符
时间限制 : 1 秒
内存限制 : 32 MB
统计一个给定字符串中指定的字符出现的次数。
题目输入
测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到'#'时输入结束,相应的结果不要输出。
题目输出
对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
c0 n0
c1 n1
c2 n2
...
其中ci是第1行中第i个字符,ni是ci出现的次数。
输入/输出样例
输入格式
I THIS IS A TEST i ng this is a long test string #
输出格式
I 2 i 3 5 n 2 g 2
C语言解答
#include <stdio.h> #include <string.h> int main(void) { char str[6],str1[81]; char *p,*q; int count=0; while(gets(str)) { if(strcmp(str,"#")==0) { break; } gets(str1); p=str; q=str1; while(*p) { q=str1; count = 0; while(*q) { if(*p == *q) { count++; } q++; } printf("%c %d\n",*p,count); p++; } } return 0; }
C++解答
#include <stdio.h> int main(){ char str1[10], str2[100]; while(gets(str1) && str1[0]!='#'){ gets(str2); int i = 0; while(str1[i]){ int j=0, count=0; while(str2[j]){ if(str1[i] == str2[j]){ count++; } j++; } printf("%c %d\n", str1[i], count); i++; } } return 0; }
Java解答
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in) ; while(true){ String str = s.nextLine() ; if(str.equals("#")){ break ; } String ss = s.nextLine() ; char a[] = ss.toCharArray() ; int temp = 0 ; char []c = str.toCharArray() ; for (int i = 0; i < c.length; i++) { for (int j = 0; j < a.length; j++) { if(c[i]==a[j]){ temp++ ; } } System.out.println(c[i]+" "+temp) ; temp = 0; } } } }