Java study notes (2): string (1)

1. Basic operation of string reading and output

import java.util.Scanner;
public class Stringg {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();//字符串输入
        System.out.println(line);
    }
}

2. Use of String class

  1. Four structures of the String class (only three are listed, and there is another byte structure that is not commonly used)
public class Stringg {
    
    
    public static void main(String[] args) {
    
    
        //第一种:直接赋值
        String l1 = "ywq";
        System.out.println("l1:"+l1);
        //第二种:无参构造
        String l2 = new String();
        l2 = "ywq";
        System.out.println("l2:"+l2);
        //第三种:传进字符数组
        char[] m= {
    
    'y','w','q'};
        String l3 = new String(m);
        System.out.println("l3:"+l3);
    }
}

2. String comparison

public class Stringg {
    
    
    public static void main(String[] args) {
    
    
        char[] ch = {
    
    'a','b','c'};
        String y = "abc";
        String w = "abc";
        String q = new String(ch);
        String l = new String(ch);
        //第一种:使用==进行比较,其比较的是地址值
        System.out.println(y == w);
        System.out.println(q == l);
        //第二种:使用equals进行比较,其比较的是字符串的值
        System.out.println(y.equals(w));
        System.out.println(q.equals(l));
    }
}
true
false
true
true

Here we have to talk about the structural characteristics of String. If you use direct assignment to construct, if the assignment of two String objects is the same, their storage address values ​​will also be the same, so y = =w will output true.
Example: User password input comparison

import java.util.Scanner;

public class Stringg {
    
    
    public static void main(String[] args) {
    
    
       String rightmima = "ywqwan";
       Scanner in = new Scanner(System.in);
       for(int i=0;i<3;i++)
       {
    
    
           String shu = in.nextLine();
           if(rightmima.equals(shu)&&i<3)
           {
    
    
               System.out.println("成功登入");
               break;
           }else if(!rightmima.equals(shu)&&i<2)
           {
    
    
               System.out.println("密码错误,请再次输入密码");
           }else
           {
    
    
               System.out.println("密码错误达到最大次数,无法验证");
           }
       }
    }
}

3. Traversal of strings (using charAt member function)

public class Stringg {
    
    
    public static void main(String[] args) {
    
    
        String love = "ywqwan";
        for (int i = 0; i < love.length(); i++) {
    
    
            System.out.println(love.charAt(i));
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_51677496/article/details/112981815