JAVA to improve the character string

Recently I learned the JAVA String class and wrote a blog to record the study notes, mainly introducing Java strings from five parts, (1) Introduction to String String (2) String String Common Methods (3) String String Conventional Operations such as Truncating and Finding Partitioning, etc., (4) the storage characteristics and immutability of strings, (5) comparison between String, StringBuilder, and Stringbuffer.

(1) Introduction to String

In JAVA, we use String to represent strings, such as "abd", "132asdjkdv", and so on. All string literals (for example "abc") in Java programs are implemented as instances of this class.

String is a fianl class that represents an immutable sequence of characters. The strings are unchanged; their values ​​cannot be changed after creation. The string buffer supports variable strings. Because String objects are immutable, they can be shared. E.g:

     String str = "abc";

Is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);

The characteristics of the string:

  1. The content of the string is never changeable after it is created. (Emphasis)
  2. Because the string is immutable after it is created, the string can be shared.
  3. The result of string processing is equivalent to char[] character array, but the underlying principle is byte[] byte array.
  4. The string object created by new, each time new will apply for a piece of memory space, although the content is the same, but the address value is different,
  5. The string given in the form of "", as long as the character sequence is the same (the order and case are exactly the same), no matter how many times it appears in the program code, the JVM will only create a String object and place it in the string constant pool of the heap memory.

 Points to note in String application

  • String s1 = "a"; Description: A string with the literal "a" is created in the string constant pool.
  •  s1 = s1 + "b"; Explanation: In fact, the original "a" string object has been discarded, and now a string s1+"b" (that is, "ab") is generated in the heap space. If these operations that change the content of the string are executed multiple times, a large number of duplicate string objects will be stored in memory, which reduces efficiency. If such an operation is placed in a loop, it will greatly affect the performance of the program.
  •  String s2 = "ab"; Description: directly create a string with the literal "ab" in the string constant pool.
  •  String s3 = "a" + "b"; Description: s3 points to the "ab" string that has been created in the string constant pool. String s4 = s1.intern(); Description: After calling intern() for the s1 object in the heap space, the "ab" string that already exists in the constant pool will be assigned to s4.

(Two) String commonly used methods

The commonly used methods of the String class in Java are as follows:

Program example:

package strings;

/**
 * Created with IntelliJ IDEA.
 * User:  yongping Li
 * Date: 2020/11/14
 * Time: 10:47
 * Description: No Description
 */
/*
 String类适用于描述字符串事物。那么它就提供了多个方法对字符串进行操作。

 常用的方法如下:

 1、获取:
 	1.1 字符串中包含的字符数,也就是字符串的长度。
 		int length():获取长度。
 	1.2 根据位置获取该位置上的某个字符。
 		char charAt(int index):返回指定索引处的char值。
 	1.3 根据字符获取该字符在字符串的位置。
 		int indexOf(String str):返回的是str在字符串中第一次出现的位置。
 		int indexOf(int ch,int fromIndex):从fromIndex指定位置开始,获取ch在字符串中出现的位置。
 		int lastIndexOf(int ch):反向索引一个字符出现的位置

 2、判断:
 	2.1  字符串中是否包含某一个子串。
 		boolean contains(str);
 		特殊之处:indexOf(str):可以索引str第一次出现的位置,如果返回-1表示该str不在字符串中存在。
 				  所以,也可以用于对指定判断是否包含。
 				 if(str.indexOf("aa")!=-1)
 				  而且该方法既可以判断,又可以获取出现的位置
 	2.2 字符中是否有内容。
 		boolean isEmpty():原理就是判断长度是否为0.
 	2.3 字符串是否是以指定内容开头。
 		boolean startsWith(str);
 	2.4 字符串是否是以指定内容结尾。
 		boolean endsWith(str);
 	2.5判断字符串内容是否相同。复写Object类中的equals方法。
 		boolean equals(str);
 	2.6 判断内容是否相同,并忽略大小写
 		boolean equalsIgnoreCase();

 3、转换
 	3.1 将字符数组转换成字符串。
 		构造函数: String(char[])
 				  String(char[],offset,count):将字符数组中的一部分转换成字符串。
 		静态方法:
 				 static String copyValueOf(char[]);
 				 static String copyvalueOf(char[] data, int offset, int count);
 	3.2 将字符串转换成字符数组(重点)。
 				char[] toCharArray();
 	3.3 将字节数组转换成字符串。
 				 String(byte[])
 				 String(byte[],offset,count):将字节数组中的一部分转换成字符串。
 	3.4 将字符串转换成字节数组
 	3.5 将基本数据类型转换成字符串。
 		String valueOf(int);
 		String valueOf(double);

 		特殊:字符串和字节数组在转换过程中是可以指定编码表的。

 4、替换
 		String replace(oldchar,newchar);
 5、切割
 		String[] split(regex);
 6、子串            获取字符串中的一部分
 		String substring(begin);
 		String substring(begin,end);
 7、转换,去除空格,比较
 	7.1 将字符串转成大写或者小写。
 		String toUpperCase();
 		String toLowerCase();
 	7.2 将字符串两端的多个空格去除。
 		String trim();
 	7.3 将两个字符串进行自然顺序的比较。
 */

public class StringDemo {
    //转换,去除空格,比较
    public static void method_7(){
        String s="Hello Java";
        sop("原字符串为:"+s);
        //转换大小写
        sop(s.toUpperCase());
        sop(s.toLowerCase());
        //去除空格
        sop(s.trim());

        //字符串比较
        String s1="acc";
        String s2="aaa";
        sop(s1.compareTo(s2));
    }
    //子串         获取字符串中的一部分
    public static void method_sub(){
        String s="abcdefghijklmnopqrstuvwxyz";
        sop("原字符串为");
        sop(s);
        String s1=s.substring(9); //从指定位置到结尾。如果角标不存在,则会出现字符串角标越界异常。
        sop("获取的子串s1为:");
        sop(s1);
        String s2=s.substring(7,20); //包含头,不包含尾。 获取整个字符串:s.substring(0,s.length());
        sop("获取的子串s2为:");
        sop(s2);
    }
    //切割
    public static void method_split(){
        String s="zhangsan,lisi,wangwu";
        String[] arr=s.split("a");
        sop("原字符串为:");
        sop(s);
        sop("切割后的字符串为:");
        for(int x=0;x<arr.length;x++)
        {
            System.out.print(arr[x]+" ");
        }
        System.out.println();
    }
    //判断
    public static void method_is(){
        String str="ArrayDemo.java";
        String str1="arraydemo.java";
        //判断文件名称是否以Array开头
        sop(str.startsWith("Array"));
        //判断文件名称是否是以.java结尾
        sop(str.endsWith(".java"));
        //判断文件名称中是否包含Demo
        sop(str.contains("Demo"));
        //判断两个文件名是否相同(区分大小写)
        sop(str.equals(str1));
        //判断两个文件名是否相同(不区分大小写)
        sop(str.equalsIgnoreCase(str1));
    }
    //获取
    public static void method_get(){
        String str="abcdeakpf";
        sop("字符串为:"+str);
        //长度
        sop("字符串的长度为:"+str.length());
        //根据索引获取字符
        sop("角标为四的位置上的字符为:"+str.charAt(4));//当访问到字符串中不存在的角标时,会发生 StringIndexOutOfBoundsException异常
        //根据字符获取索引
        sop("从角标为3的位置开始往后索引 a 出现的位置为:"+str.indexOf('a',3));//如果没有找到返回-1
        //反向索引一个字符出现的位置
        sop("从字符串右面开始索引第一个a出现的位置为:"+str.lastIndexOf("a"));
    }
    //转换
    public static void method_trans(){
        char[] arr={'a','b','c','d','e','f','g','h'};
        String str="jkasdhavsgjv";
        char[] a=str.toCharArray();
        //字符串操作
        System.out.print("将字符串转换为字符数组为:[");
        for(int x=0;x<a.length;x++)
        {
            if(x<a.length-1)
                System.out.print(a[x]+",");
            else
                System.out.print("]");
        }
        System.out.println();
        //字符数组操作
        System.out.print("字符数组为:[");
        for(int x=0;x<arr.length;x++)
        {
            if(x<arr.length-1)
                System.out.print(arr[x]+",");
            else
                System.out.print("]");
        }
        System.out.println();
        String s=new String(arr);
        sop("转换成字符串为:"+s);
        //获取从角标为1的位置的字符开始三个字符
        String s1=new String(arr,1,3);
        sop("从角标为1的位置的字符开始三个字符组成的字符串为:"+s1);
    }
    //替换
    public static void method_replace(){

        String s="      hello java     ";

        String s1=s.replace('a', 'n'); //如果要替换的字符不存在,则返回的还是原字符串

        sop("原来的字符串为:"+s);

        sop("替换字符后的字符串为:"+s1);

    }
    //主函数
    public static void main(String[] args) {
        method_get();
        method_is();
        method_trans();
        method_replace();
        method_split();
        method_sub();
        method_7();
    }
    //输出结果
    public static void sop(Object obj){
        System.out.println(obj);
    }
}

operation result:

字符串为:abcdeakpf
字符串的长度为:9
角标为四的位置上的字符为:e
从角标为3的位置开始往后索引 a 出现的位置为:5
从字符串右面开始索引第一个a出现的位置为:5
true
true
true
false
true
将字符串转换为字符数组为:[j,k,a,s,d,h,a,v,s,g,j,]
字符数组为:[a,b,c,d,e,f,g,]
转换成字符串为:abcdefgh
从角标为1的位置的字符开始三个字符组成的字符串为:bcd
原来的字符串为:      hello java     
替换字符后的字符串为:      hello jnvn     
原字符串为:
zhangsan,lisi,wangwu
切割后的字符串为:
zh ngs n,lisi,w ngwu 
原字符串为
abcdefghijklmnopqrstuvwxyz
获取的子串s1为:
jklmnopqrstuvwxyz
获取的子串s2为:
hijklmnopqrst
原字符串为:Hello Java
HELLO JAVA
hello java
Hello Java
2

Process finished with exit code 0

 

(3) Conventional operation of strings

The regular operations of a string include search, intercept, and segmentation. These corresponding methods in the String class can be called directly, or a comprehensive call of several methods.

package strings;

/**
 * Created with IntelliJ IDEA.
 * User:  yongping Li
 * Date: 2020/11/14
 * Time: 10:53
 * Description: No Description
 */
public class  newStringDemo {

    public static void main(String[] args) {
        /*
         * 查找子串
         */
        String str1="dwqae12232aebdalf";
        //查找指定字符第一次出现的位置
        int first1=str1.indexOf(97);//参数为字符的ascii码
        //查找指定字符串第一次出现的位置
        int first2=str1.indexOf("12");
        //查找指定字符第一次出现的位置,从索引处开始(包括索引处)
        int first3=str1.indexOf(97, 0);
        //查找指定字符串第一次出现的位置,从索引处开始(包括索引处
        int first4=str1.indexOf("12232",0);
        System.out.println("first1="+first1);
        System.out.println("first1="+first2);
        System.out.println("first1="+first3);
        System.out.println("first1="+first4);
        System.out.println("-------------");
        /*
         * 截取字符串
         */
        //从索引处到末尾(不包括索引处)
        String substr1=str1.substring(5);
        //指定区间(包括结束索引处)
        String substr2=str1.substring(5, 10);
        System.out.println("substr1="+substr1);
        System.out.println("substr2="+substr2);
        System.out.println("-------------");
        /*
         * 分割字符串
         */
        //以a为分割字符
        String[] splitstr=str1.split("a");
        for(String res : splitstr){
            System.out.println(res);
        }
        //注:如果分割字符为正则表达式里的字符,则需要"\"做转义
    }

}

The results of the operation are as follows·:

first1=3
first1=5
first1=3
first1=5
-------------
substr1=12232aebdalf
substr2=12232
-------------
dwq
e12232
ebd
lf

Process finished with exit code 0

(4) The storage characteristics and immutability of strings

In the memory allocation of Java, there are a total of 3 types of constant pools, namely Class constant pool , runtime constant pool , and string constant pool. The memory structure of JVM is:

Memory analysis during String definition:

Definition of String class

String s1="abc";

String s2="abc";

s1="hello";

String memory analysis:

 

Comparison of two definition methods of String

String S="abc";
String s=new String("abc");

Memory analysis:

 

Comparison of String and char array:

//String的两种定义方式
String a="abc";
String s=new String("abc");


char[] arr={'a','b'};

char [] ass={'a','b','c','d','e'};

String s=new String(arr,13,43);

Memory analysis:

 In summary, String s="adb", abd is stored in the constant pool, String s=new String("abd"), s points to the value in the heap, and value points to abd in the constant pool;

The immutability of String means that every method in String that seems to modify the value of String actually creates a brand new String object to contain the modified String object, while the original String object has not changed.

Program example:

package strings;//: strings/Immutable.java


public class Immutable {
  public static String upcase(String s) {
    return s.toUpperCase();
  }
  public static void main(String[] args) {
    String q = "howdy";
    System.out.println(q); // howdy
    String qq = upcase(q);
    System.out.println(qq); // HOWDY
    System.out.println(q); // howdy
  }
} /* Output:
howdy
HOWDY
howdy
*///:~

The result of the operation is

Code example:

package strings;

/**
 * Created with IntelliJ IDEA.
 * User:  yongping Li
 * Date: 2020/11/14
 * Time: 15:10
 * Description: No Description
 */
public class StringTest {
    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "bcd";

        System.out.println(str1);
        System.out.println(str2);

        str1 = str2;
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str1 == str2);

        //.......
        str1 = new String("bcd");
        System.out.println(str1);
        System.out.println(str1 == str2);
    }

}

operation result:

Run process analysis:

Start running the program:

String str1 = "abc";
String str2 = "bcd";

(From a memory perspective) When using literal values ​​to create a String, the compiler will look in the static method area (string constant pool) to find whether there are literal values ​​(here, abc and bcd). If not, it will be in a static method. Create in the area (string constant pool), and assign values ​​to our str1 and str2 (assign the address of abc to str1, the same is true for str2);

å¨è¿éæå ¥ å¾çæè¿ °

 

then

str1 = str2;

å¨è¿éæå ¥ å¾çæè¿ °

When the object is subsequently created

str1 = new String("bcd");

å¨è¿éæå ¥ å¾çæè¿ °

When the two are compared:

str2 = new String("bcd");
System.out.println(str1 == str2);

å¨è¿éæå ¥ å¾çæè¿ °

 

(5) Comparison between String StringBuilder and StringBuffer

StringBuilder and StringBuffer are improvements to String. We know that String has immutability and length determinism, that is, an immutable character sequence. Then, how to define a variable character sequence, java.lang.StringBuffer represents a variable character sequence , You can add or delete the string content, and no new objects will be generated at this time. Many methods are the same as String. When passed as a parameter, the value can be changed inside the method.

The StringBuffer class is different from String in that its objects must be generated using a constructor. There are three constructors:

StringBuffer(): A string buffer with an initial capacity of 16

StringBuffer(int size): Construct a string buffer with a specified capacity

StringBuffer(String str): Initialize the content to the specified string content

Common method

StringBuffer append(xxx): Provides a lot of append() methods for string splicing

StringBuffer delete(int start,int end): delete the content at the specified position

StringBuffer replace(int start, int end, String str): replace the [start, end) position with str

StringBuffer insert(int offset, xxx): insert xxx at the specified position StringBuffer reverse(): reverse the current character sequence

 

StringBuilder and StringBuffer are very similar, both represent variable character sequences, and the methods for providing related functions are also the same.

 

Interview questions: Compare String, StringBuffer, StringBuilder

String (JDK1.0): immutable character sequence

StringBuffer (JDK1.0): Variable character sequence, low efficiency, thread safety

StringBuilder (JDK 5.0): Variable character sequence, high efficiency, unsafe thread. Note: If passed as a parameter, String inside the method will not change its value, StringBuffer and StringBuilder will change its value.

Inheritance structure: 

è¿éåå¾çæè¿ °

Comparison of the three

1) String is an immutable character sequence, StringBuilder and StringBuffer are variable character sequences.
2) Execution speed StringBuilder> StringBuffer> String.
3) StringBuilder is not thread-safe, StringBuffer is thread-safe

(6) Conversion between String and basic data types

 

 

 

Guess you like

Origin blog.csdn.net/weixin_41792162/article/details/109688088