【编程题m_0013】计算字符个数

链接:https://www.nowcoder.com/questionTerminal/a35ce98431874e3a820dbe4b2d0508b1
来源:牛客网
 

写出一个程序,接受一个有字母和数字以及空格组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。不区分大小写。

输入描述:

输入一个有字母和数字以及空格组成的字符串,和一个字符。

输出描述:

输出输入字符串中含有该字符的个数。

示例1

输入

ABCDEF
A

输出

1

解题思路:逐个进行不区分大小写的比较,同时统计相等的次数

package BiShiTi;

import java.util.Scanner;

public class m_0013 {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner scan = new Scanner(System.in);
		String targetStr = scan.nextLine();
		String targetChar = scan.nextLine();
        
		int counter = countTargetChar(targetStr, targetChar);
		System.out.println(counter);
	}
	
	static int countTargetChar(String targetStr, String targetChar ){
		int targerStrLen = targetStr.length();
		
		int counter = 0;
		char t;
		for(int i = 0; i < targerStrLen; i++){
			t = targetStr.charAt(i);
			if (targetChar.toUpperCase().equals(String.valueOf(t)) || targetChar.toLowerCase().equals(String.valueOf(t))) {
				counter ++;
			}
		}
		
		return counter;
	}

}

猜你喜欢

转载自my.oschina.net/MasterLi161307040026/blog/1811755