Java_13.1.1 字符串的应用

1获取一个字符串中,另一个字符串出现的次数

  思想:
        1. indexOf到字符串中到第一次出现的索引
        2. 找到的索引+被找字符串长度,截取字符串
        3. 计数器++

package demo1;

public class Demo1 {
	public static void main(String[] args) {
		int num = getStringCount("javajavajavajava","java");
		System.out.println(num);
	}
	public static int getStringCount(String str,String str1) {
		int num = 0;
		int index = 0;
		while((index=str.indexOf(str1))!=-1) {
			num++;
			str = str.substring(index+str1.length());
		}
		return num;
	}
}

 

2.将字符串的首字母转成大写,其他内容转成小写

package demo1;

public class Demo1 {
	public static void main(String[] args) {
		String str = "abHUJfi35ki6";
		String first = str.substring(0,1);
		String after = str.substring(1);
		first = first.toUpperCase();
		after = after.toLowerCase();
		System.out.println(first+after);
	}
}

 

3.获取指定字符串中,大写字母、小写字母、数字的个数。

package demo1;

public class Demo1 {
	public static void main(String[] args) {
		String str = "haHA12";
		int upper = 0;
		int lower = 0;
		int num = 0;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if(c>='A'&&c<=90){
				upper++;
			}else if(c>=97 && c<=122){
				lower++;
			}else if(c>=48 && c<='9'){
				num++;
			}
		}
		System.out.println("大写字母:"+upper);
             System.out.println("小写字母:"+lower);
             System.out.println("数字:"+num); } }

 

原文地址:https://www.cnblogs.com/smxbo/p/10666462.html