首页 > 试题广场 >

统计字符

[编程题]统计字符
  • 热度指数:18850 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
    统计一个给定字符串中指定的字符出现的次数。

输入描述:
    测试输入包含若干测试用例,每个测试用例包含2行,第1行为一个长度不超过5的字符串,第2行为一个长度不超过80的字符串。注意这里的字符串包含空格,即空格也可能是要求被统计的字符之一。当读到'#'时输入结束,相应的结果不要输出。


输出描述:
    对每个测试用例,统计第1行中字符串的每个字符在第2行字符串中出现的次数,按如下格式输出:
    c0 n0
    c1 n1
    c2 n2
    ... 
    其中ci是第1行中第i个字符,ni是ci出现的次数。
示例1

输入

I
THIS IS A TEST
i ng
this is a long test string
#

输出

I 2
i 3
  5
n 2
g 2
def calStr(char, s):
    if char == "#":
        return None
    ltemp = [0 for _ in range(128)]
    for i in s:
        ltemp[ord(i)] += 1
    for j in char:
        num = ltemp[ord(j)]
        print("%s %d" % (j, num))


while True:
    try:
        char = input()
        s = input()
        calStr(char, s)
    except:
        break

发表于 2022-08-03 11:31:31 回复(0)
while True:
    try:
        index=input()
        if index!='#':
            inp=list(input().strip())
            index_list=list(index)
            dict1={}
            for i in index_list:
                if i not in dict1:
                    dict1[i]=inp.count(i)
            for i in index_list:
                print(i+' '+str(dict1[i]))

    except:
        break
发表于 2019-08-04 13:28:29 回复(0)
while True:
    try:
        string1 = input()
        if string1 == '#':
            break
        string2 = input()
        for i in string1:
            print("%s %d" % (i,string2.count(i)))
    except Exception:
        break
编辑于 2018-09-25 14:50:24 回复(0)

python解法,应该是最简单了的吧

while True:
    try:
        a,b=input(),input()
        for i in a:
            print(i+" "+str(b.count(i)))
    except:
        break
编辑于 2017-10-06 21:24:09 回复(0)
from collections import Counter
try:
    while 1:
        Query = raw_input()
        if Query == '#':
            break
        s = raw_input()
        Table = Counter(s)
        for i in Query:
            print i, Table[i]
except:
    pass

发表于 2016-12-27 08:36:18 回复(0)