java---String commonly used classes

String commonly used classes

Topic 1:

1.编写一个程序,让用户输入一个字符串,随即在控制台输出这个字符串中的 英文字母个数,数字个数。

Effect display:
Insert picture description here
Code implementation:

		 Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String a = sc.next();
        int letter=0;
        int num=0;
        char[] a1 =a.toCharArray();		//将输入的字符串转换为字符数组
        for (int i = 0; i < a.length(); i++) {
    
    
            if (Character.isLetter(a1[i])){
    
         //isLetter是用来判断字符串中的字母
                letter++;
            }else if (Character.isDigit(a1[i])){
    
        //isDigit是用来判断字符串中的数字        
                num++;
            }
        }
        System.out.println("输入字符串中字母有"+letter+"个,数字有"+num+"个");

Topic 2:

2.编写一个程序,让用户先后输入两个字符串,一个长的,一个短的,例如:“how do you do”和“do;然后输出短的那个字符串在长的字符串中出现的次数。

Effect display:
Insert picture description here
Code implementation:

Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个比较的字符串:");
        String m = sc.nextLine();
        System.out.println("请输入第二个比较的字符串:");
        String n = sc.nextLine();
        int num1=0;
        for (int i = 0; i <= (m.length()-n.length()); i++) {
    
    
            if (n.equals(m.substring(i,i+n.length()))){
    
    		 //截取字符串中相同的内容
                num1++;
            }
        }
        System.out.printf("第二个字符串在第一个字符串中出现的次数为:%d次",num1);

supplement:

Commonly used classes of String
1. Length length()
2. Concatenation str.concat(str2)
3. Formatting

 //方式一
System.out.printf("大家好,我的名字叫:%s,我今年:%d岁了,我的存款有:%f %n","曹操",36,999.99);
//方式二
String s = String.format("大家好,我的名字叫:%s,我今年:%d岁了,我的存款有:%f","曹操",36,999.99);
System.out.println(s);

4. charAt(index) returns the character at the specified index
5. indexOf(str) returns the index of the first occurrence of the specified string in this string
6. compareTo(str2) compares two strings
7. equals() And equalsIgnoreCase()
8. getBytes() uses the default character set to convert a string into a byte array, which will be used in the IO stream
9. toCharArray() Convert a string to a character array
10. Intercept: subString()
11. Convert to Case toLowerCase() toUpperCase()
12. Blank before and after interception trim()
13. Replace: replace()
14. Split: split()
15. Regular matching matches(String reg) returns boolean

Guess you like

Origin blog.csdn.net/weixin_44889894/article/details/111400550