统计大写字母个数

统计大写字母个数是一个比较简单的Java练习题,这里是想列举几种实现方式,供参考交流学习。

题目描述:找出给定字符串中大写字符(即'A'-'Z')的个数。

题解

从题目中找几个关键字 1,字符串;2,大写字符

从字符串中找大写字符,第一个点,把字符串转换为字符;第二个点,找字符中的大写字符。

从分析看,这个题目主要涉及到String、char、Character 三种类型的变量,答案中应该包含这三种变量中的一种或多种。

1、 把字符串转换为字符

String类的底层实现是用字符数组类存储字符信息的

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

在String中找可以转换为char的方法有charAt(int index) 和 toCharArray(),分别返回字符串中指定位置的字符和一个字符数组

    /**
     * Returns the {@code char} value at the
     * specified index. 
     */
    public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }   

    /**
     * Converts this string to a new character array.
     */
    public char[] toCharArray() {
        // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }

这里有两种方法,将字符串转换为字符,分别为 charAt(int index) 和 toCharArray()

2、找字符中的大写字符

拿到字符后,判断其是否为大写字符,有几种判断方式

  1. 比较当前字符与大写字母的ASCII码值范围
  2. 利用Character类静态方法 isUpperCase判断
  3. 比较当前字符与大写字母范围,与1类似

3、编码

根据上面两步的题解,可以组合出答案

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 统计大写字母个数
 */
public class CountUperLetter {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		
		while ((input = br.readLine()) != null) {
			int index = 0;
			
			/**
			 * method 1 
			 * 获取字符串转换字符用toCharArray()
			 * 利用大写字母对应的ASCII码值比较
			 */
//			for (char ch : input.toCharArray()) {
//				if (ch >= 65 && ch <= 90) {
//					index++;
//				}
//			}
			
			/**
			 * method 2 
			 * 获取字符串转换字符用toCharArray()
			 * 利用character包装类Character类静态方法 isUpperCase判断
			 */
//			for (char ch : input.toCharArray()) {
//				if (Character.isUpperCase(ch)) {
//					index++;
//				}
//			}
			
			/**
			 * method 3 
			 * 获取字符串转换字符用toCharArray()
			 * 直接比对字符与大写字母的范围
			 * 此方法与method 1 类似
			 */
//			for (char ch : input.toCharArray()) {
//				if (ch >= 'A' && ch <= 'Z') {
//					index++;
//				}
//			}
			
			/**
			 * method 4 
			 * 获取字符方式采用charAt方法
			 * 利用大写字母对应的ASCII码值比较
			 */
			for (int i=0; i<input.length(); i++) {
				char ch = input.charAt(i);
				if (ch >= 65 && ch <= 90) {
					index++;
				}
			}
			
			System.out.println(index);
		}
	}

}

编码还可以有method5 和 method6,分别把method2 和 method3中获取字符的方式改为charAt方式,与前面的相似度太高,就不贴代码了。

这里主要聊字符串到字符以及字符和大写字符的处理,输入的BufferedReader 可以替换为Scanner 就不赘述了。

以上,个人的整理,您是否有其它的思路,欢迎碰撞。谢谢。

猜你喜欢

转载自blog.csdn.net/magi1201/article/details/113282114