Java learning - string processing

String declaration

String userName="Zhang San";
//perhaps
String otherName=new String("Li Si");

String connection

Format: string1.concat(string2)
For example:

public class yyy {
    public static void main(String[] args) {
        String str1="hello ";
        String str2="world!";
        String str3=str1.concat(str2);
        System.out.println(str3);

    }
}

Run result: hello world!
Or use the '+' sign, but pay attention to the order

public class yyy {
    public static void main(String[] args) {
        //Operation before character connection
        System.out.println(10+1.28+"hhh");
        //Direct character connection
        System.out.println("hhh"+10+1.28);
    }
}

Operation result:
11.28hhh
hhh101.28

string comparison

Format: string1.equals(string2)
For example:

public class yyy {
    public static void main(String[] args) {
        String str1="hello";
        String str2="Hello";
        System.out.println(str1.equals(str2));
    }
}

Run result: false
There is also a comparison that ignores case
For example:

public class yyy {
    public static void main(String[] args) {
        String str1="hello";
        String str2="Hello";
        System.out.println(str1.equalsIgnoreCase(str2));
    }
}

Run result: true

String truncation

Format: string substring (start position) or string substring (start position, end position)

For example:

public class yyy {
    public static void main(String[] args) {
        String str1="I love java";
        String subs1=str1.substring(2);
        String subs2=str1.substring(2,6);
        System.out.println(subs1);
        System.out.println(subs2);
    }
}

Operation result:
love java
love

String substitution

Format: string1.replace (character to be replaced, new character)
For example:

public class yyy {
    public static void main(String[] args) {
        String str1="aaabbbcccddd";
        char oldchar='b';
        char newchar='e';
        String str2=str1.replace(oldchar, newchar);
        System.out.println(str2);
    }
}

Operation result: aaaeeecccddd

Using the StringBuffer class when strings change frequently

Tags: Java

Posted on Tue, 31 Mar 2020 19:50:02 -0700 by mistcat