四、String字符串

2018-08-21  本文已影响2人  圣贤与无赖

1. 获取指定字符串中,大写字母、小写字母、数字的个数。
思路:
1.为了统计大写字母、小写字母、数字的个数。创建3个计数的变量。
2.为了获取到字符串中的每个字符,进行字符串的遍历,得到每个字符。
3.对得到的字符进行判断,如果该字符为大写字母,则大写字母个数+1;如果该字符为小写字母,则小写字母个数+1;如果该字符为数字,则数字个数+1。
4.显示大写字母、小写字母、数字的个数
代码:

public class StringDemo04 {
    //获取指定字符串中,大写字母、小写字母、数字的个数。
    public static void method(String str){
        //1.为了统计大写字母、小写字母、数字的个数。创建3个计数的变量。
        int bigCount = 0; 
        int smallCount = 0;
        int numberCount = 0;
        //2.为了获取到字符串中的每个字符,进行字符串的遍历,得到每个字符。
        for (int i = 0; i < str.length(); i++) {
            //得到每个字符
            char ch = str.charAt(i);
            //3.对得到的字符进行判断,
            if (ch >= 'A' && ch <= 'Z') { // 'A' -- 'Z'
                bigCount++;
            } else if( ch >= 'a' && ch <= 'z' ){ // 'a' -- 'z'
                smallCount++;
            } else if(ch >= '0' && ch <= '9' ){// '0' -- '9'
                numberCount++;
            }
        }
        //4.显示大写字母、小写字母、数字的个数
        System.out.println("大写字母=" + bigCount);
        System.out.println("小写字母=" + smallCount);
        System.out.println("数字的个数=" + numberCount);
    }
    
    
    public static void main(String[] args) {
        String str = "Hello12345World";
        method(str);
    }
}



2. 查询字符串“hellojava,nihaojava,javazhenbang”中查询出现“java”的次数。
思路:

  1. 替换"java" -->""
    String replace(String old,String new) 在该字符串中, 将给定的旧字符串,用新字符串替换
  2. 进行两个字符串长度相减,等到一个长度差值,如长度为12。
  3. 长度差值 除 "java”字符串的长度, 得到的就是 出现的次数了
    代码:
public class StringDemo06 {
    private static void method(String str, String key) {
        //1替换"java" -->"",如“hellojava,nihaojava,javazhenbang” --> “hello,nihao,zhenbang”
        String newString = str.replace(key, "");
        //2. 进行两个字符串长度相减,等到一个长度差值,如长度为12。
        int length = str.length() - newString.length();
        //3. 长度差值 除  "java”字符串的长度, 得到的就是 出现的次数了
        int count = length / key.length();
        System.out.println(count);
    }
    
    public static void main(String[] args) {
        String str = "hellojava,nihaojava,javazhenbang,hellojava,hellojava,hellojava,hellojavahellojava";
        String key = "java";
        method(str , key);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读