Let's take a look at the String class in Java! ! !

Simple understanding of the String class in Java

First, understand the importance of the String class

Strings have already been involved in C language, but in C language to express strings can only use character arrays or character pointers, you can use the string series functions
provided by , but this kind of data The method of separating from the method of operating data does not conform to the idea of ​​​​object-oriented, and the application
of strings is very extensive, so the Java language specifically provides the String class.

So here, the blogger mentioned that String in Java is a reference data type, not a basic data type like int, char, float, etc. ! ! !

(1) The string "" is also an object in Java, and the description class of the object, java.lang.String, provides many methods to manipulate strings.

(2) The frequency of use is very high: height, age, education, work experience, marital status, life goals.

(3) Learn to learn the String class well, provide operation methods, and the methods must be proficient.


Second, the structure of the string

The first:

String str1 = "hello"; This is the most concise way of expression, note that the address of the string is stored in str1.

The second type:

String str2 = new String(“world”);

The third type:

char[] chars = {'j','a','v','a'};

String str3 = new String(chars);

Summary: (1) These three ways to create a string are the same, and the address of the string is stored in the object.

​( 2) The string in java does not have '/0' at the end like in C language

How strings are stored in memory (ignoring the problem of constant pool here):

insert image description here


3. Commonly used operations on strings

1. Comparison of String objects

Demo:

String str1 = new String("hello");
String str2 = new String("world");
System.out.println(str1.equals(str2));


//代码运行的结果为:false

This is because the address of the new object is different, and before equals is not rewritten, it is judged according to the address of the object, so the output here is false.

System.out.println(str1.equalsIngnoreCase(str2));This statement ignores the size of the strings for comparison.

2. Compare the size of two strings

Demo:

       String s1 = new String("hello");
       String s2 = new String("world");
       int ret = s1.compareTo(s2);
       if(ret>0) {
    
    
           System.out.println("s1>s2");
       }else if(ret<0) {
    
    
           System.out.println("s1<s2");
       }else {
    
    
           System.out.println("s1=s2");
       }


//运行结果为:s1<s2

About the compareTo function, this function is used to compare the size of two strings, starting from the first character, according to the ascll code value comparison, returns an integer compareToIngnoreCase function ignores case for comparison.

3. String search

(1) Find the element according to the subscript

Demo:

       String str = "abcdef";
       for(int i = 0;i<str.length();i++) {
    
    
           char ch = str.charAt(i);//chatAt函数是返回下标为i的字符
           System.out.print(ch );
       }


//这里输出的结果为a b c d e f

(2) Find the subscript of a character in the string

String str = "abcdef";
System.out.print(str.indexOf('c') );

//2

This function is to find the target character and return the subscript of the target character. But if the target character has multiple identical characters, the subscript of the first character will be returned.

String str = "abcdefcc";
System.out.print(str.indexOf('c',3) );

//6

Start searching from the position with subscript 3

(3) Find the string in the string

Demo:

String str = "abcdefcc";
System.out.print(str.indexOf("abc"));

//0

Returns the index of the first character of the string found first.

String str = "abcdefabc";
System.out.print(str.indexOf("abc",3));

//6

Find the string starting from the character whose subscript position is 3.

(4) Find characters from back to front

Demo:

String str = "abcdef";
System.out.print(str.lastIndexOf('c'));

//2

This function is used to find the target character from the back to the front and return the subscript.

String str = "abcdcefc";
System.out.print(str.lastIndexOf('c',5));

//4

Search from the back to the front from the position with subscript 5, find and return the subscript.

(5) Find the string from the back to the front

Demo:

String str = "abcdcefabcfsdfabc";
System.out.print(str.lastIndexOf("abc"));

//14

Find the string from the back to the front, find and return the first character subscript of this string.

String str = "abcdcefabcfsdfabc";
System.out.print(str.lastIndexOf("abc",12));

//7

Find the string starting from the position where the subscript is 12, find and return the subscript of the first character of this string.

4. Conversion between types

(1) Value and string conversion

In this case, use the valueOf function, which can be followed by any data type, such as int, char, boolean, or even a class, etc.

String str = String.valueOf(1234);

String str = String.valueOf(new Integer(1234));

(2) Convert strings to other data types

In this case, use the methods in the wrapper classes of various data types, such as parseInt(), parseDouble(), etc.

double num2 = Double.parseDouble("3.14");

int num1 = Integer.parseInt("1234");

(3) Conversion between upper and lower case

Demo:

//小写-->大写
        String str1 = "hello";
        String ret1 = str1.toUpperCase();
        System.out.println(ret1);

//大写-->小写
        String str2 = "HELLO";
        String ret2 = str2.toLowerCase();
        System.out.println(ret2);

/*
HELLO
hello
*/

(4) String to array

Demo:

String str = "abcdefg";
char[] chars = str.toCharArray();
System.out.println(Arrays.toString(chars));

//[a, b, c, d, e, f, g]

The toCharArray() function converts the string into an array type, and the Arrays.toString() function outputs in the form of an array.

(5) String replacement

This function does not replace the original function, but returns a new string Demo:

        String str = "ababcbacabcdef";
        String ret = str.replace('a','q');//将字符串里面的所有'a'换成'q'
        System.out.println(ret);

        String ret2 = str.replace("ab","wz");//将字符串中的"ab"换成"wz"
        System.out.println(ret2);

        String ret3 = str.replaceAll("abc","mnpl");//将字符串中所有的"abc"换成"mnpl"
        System.out.println(ret3);
        
        String ret4 = str.replaceFirst("abc","uuuu");//将字符串中第一个"abc"换成"uuuu"
        System.out.println(ret4)
            
            
/*
qbqbcbqcqbcdef
wzwzcbacwzcdef
abmnplbacmnpldef
abuuuubacabcdef
*/

(6) String splitting

Demo:

String str = "zhangsan&wangwu";
String[] ret = str.split("&");
System.out.println(Arrays.toString(ret));

//[zhangsan, wangwu]

The split function splits the string through the characters in the brackets, and returns an array of strings.

String[] ret = str.split("&",2);The number of groups can be limited, so that it is divided into two groups

Special split:

Demo:

        String str = "127.00.0.1";
        String[] ret = str.split("\\.");
        for(String x:ret) {
    
    
            System.out.println(x);
        }

Two "\\" are equivalent to one "\", and then "\" and "." are a real ".".

Note:

  • Characters "\", "*", "+" must be added with an escape character, preceded by "\\"
  • If you want to divide according to "\", write it as "\\\\"
  • If there are multiple separators in a string, "|" can be used as a connector
    • str.split("= | &");

(7) String splitting

Demo:

        String str = "helloworld!";
        String ret1 = str.substring(1);//从下标为1的位置开始截取
        System.out.println(ret1);

        String ret2 = str.substring(1,4);//从下标为1的位置开始,取到下标为4的位置,左闭右开
        System.out.println(ret2);

/*
elloworld!
ell
*/

(8) trim function in string

Demo:

        String str = "  hello hello  ";
        String ret = str.trim();
        System.out.println(ret);

//hello hello

The trim function is to remove the spaces on the left and right sides of the string, and the spaces in the middle will not be removed


Four, StringBuffer and StringBuilder

Due to the immutable characteristics of String, in order to facilitate the modification of strings, Java also provides StringBuilder and StringBuffer classes, which are also classes and can also represent strings.

1. The difference between String, StringBuffer and StringBuilder

  • After the object of the String class is created, the content cannot be modified, but the content of the StringBuffer and StringBuilder objects can be modified after the object is created
  • Most of the functions of StringBuffer and StringBuilder are similar
  • StringBuffer adopts synchronous processing and is thread-safe
  • StringBuilder is not synchronized and not thread-safe

2. After the creation of the String object, the reason why the content cannot be changed

This is because there is a byte[] array in the String class in the source code. This array is final modified, so the array cannot be modified once it is created, and once the final modified reference points to an object, it cannot point to other objects.

Notice:The String and StringBuilder classes are not directly convertible. If you want to convert each other, you can use the following principles:

  • String becomes StringBuilder: use StringBuilder's construction method or append() method
  • StringBuilder becomes String: Call toString() method.

3. Common methods

method illustrate
StringBuff append(String str) Append at the end, which is equivalent to += of String, and can be appended: variables of boolean, char, char[], double, float, int, long, Object, String, StringBuff
char charAt(int index) Get the character at the index position
int length() Get the length of the string
int capacity() Get the total size of the underlying storage string space
void ensureCapacity(int mininmumCapacity) expansion
void setCharAt(int index,char ch) Set the character at index position to ch
int indexOf(String str) Returns the position of the first occurrence of str
int indexOf(String str, int fromIndex) Find the first occurrence of str from the fromIndex position
int lastIndexOf(String str) Returns the position of the last occurrence of str
int lastIndexOf(String str,int fromIndex) Find the last occurrence of str from the fromIndex position
StringBuff insert(int offset, String str) Insert at offset position: eight base class types & String type & Object type data
StringBuffer deleteCharAt(int index) Delete the index position character
StringBuffer delete(int start, int end) Delete the characters in the interval [start, end)
StringBuffer replace(int start, int end, String str) Replace the characters at [start, end) with str
String substring(int start) The characters from start to the end are returned as String
String substring(int start,int end) Return the characters in the range of [start, end) as String
StringBuffer reverse() reverse string
String toString() Return all characters as String

Since these methods are many, the blogger will not demonstrate them one by one here, and you can go down and knock on your own.


Well, this blog of this issue brings you a brief understanding of the String class. If you still have questions that you don’t understand or there are mistakes in the article, please send a private message to the blogger in the background! ! !

No matter how far the road is, there will be an end, no matter how long the night is, there will be an end, no matter how heavy the rain will be, there will be a stop.
insert image description here

Guess you like

Origin blog.csdn.net/m0_74968164/article/details/131643482