Javase | String string - 2

string

  • A Java string is a sequence of Unicode characters.

    For example:

    The string "Java\u2122" is composed of 5 Unicode characters J, a, v, a and (trademark) TM.
    \u2122 is the Unicode escape sequence. In Unicode, \u followed by four hexadecimal digits represents a Unicode character, and \u2122 represents "™" (trademark symbol).

  • Java does not have a built-in string type, but provides a predefined class called String in the standard Java class library. Every string enclosed in double quotes is of type String.

    For example:

    String s = ""; //空字符串
    String str ="HelloWorld";
    

Substring:

Use the substring method to extract substrings from a string

  • The substring() method of the String class can extract a substring from a larger string.

    For example:

    String str ="HelloWorld";
    String s =str.substring(0);   //创建了一个由字符“HelloWorld”组成的字符串。
    //创建了一个由字符“Hello”组成的字符串。(第一个字符的索引为0)
    String s2 =str.substring(0,5);   
    
  • Advantages of the subsString() method: easy to calculate the length of the substring. The length of subsString(a,b) is ba. For example: the length of the substring "hello" is: 5-0=5.

Two overloaded forms of substring() method

  • Extension: Two overloaded forms of substring() method:
    • 1.substring(int beginIndex):
      Starting from the specified index, intercept all subsequent characters including the execution index, and return a new string.
    • 2.substring(int beginIndex, int endIndex):
      Intercept the corresponding characters from the specified start index (beginIndex) to the end index (endIndex) (excluding the end index), and return a new string.

Splicing:

Use the + sign to concatenate (splice) two strings

  • The Java language allows you to concatenate (splice) two strings using the + sign.

    For example:

    String example = "interesting";
    String example2 = "things";
    String Infomation = example+" "+example2;
    System.out.println(Infomation); //interesting things
    
  • When you concatenate a string with a non-string, the latter is automatically converted to a string. This feature usually appears in output statements.

    For example:

    int age =20;
    String str="NL" + age;  //NL20
    

Use static join method to store and separate multiple strings

  • If you want to put multiple strings together, separated by a delimiter, you can use the static join method.

    For example:

    //用 / 将SMLXL分隔开
    String all = String.join("/","S","M","L","XL");
    System.out.println(all);  // S/M/L/XL
    

Copy/repeat a string using the repeat method

  • In Java11, a repeat() method for copying/repeating strings is provided.

    For example:

    String repeated = "Java".repeat(3); // "Java"
    System.out.println(repeated); // JavaJavaJava
    

Immutable string:

How to modify a character in a string

  • The String class does not provide a method for modifying a character in a string. String str = "Hello"; If you want to modify the content in str to "Help!", you cannot directly change the characters in the last two positions to 'p' and '!'. At this time, you can: extract the substring you want to keep, and then splice it with the substring you want to replace.

    For example:

    String str = "Hello";
    str = str.substring(0, 3)+"p!"; // “Help!”
    System.out.println(str); // Help!
    
  • Since a single character in a Java string cannot be modified, Java calls the String class object: immutable. Just like the number 3 is always the number 3, the string "Hello" always contains the characters H, e, l, l, o, and we cannot modify these values. But you can let one string refer to another string, for example: String str = "Hello"; At this time, you can let str = "Help!" directly.

Check if strings are equal:

Case sensitive detection of string equality

  • You can use the equals method to check whether two strings are equal. Returns true if the two strings are equal, false otherwise.

  • The two objects being compared can be string variables or string literals.

    For example:

    String color = "red";
    color.equals(color);//true
    "Hello".equals(color);//false
    

Case-insensitive detection of string equality

  • If you want to test whether two strings are equivalent in a case-insensitive manner, you can use the equalsIgnoreCase method.

    For example:

    "Hello".equalsIgnoreCase("hello");
    

Do not use the == operator to determine whether two strings are equal

  • Do not use the == operator to determine whether two strings are equal. This operator can only determine whether two strings are stored at the same location. Of course, if the strings are stored in the same location, they must be equal.

    However, it is entirely possible to place multiple copies of a string with equal content in different locations. If the virtual machine always shares the same substring, you can use == to check whether two strings are equal.

Empty string and Null string (null):

empty string

  • The empty string is a string of length 0. You can use the following code to determine whether a string is an empty string:

    if(str.length()==0){
           
            //长度为0,自然是空串
        //为空串
    }else{
           
           
        //不为空串
    }
                
    if(str.equals("")){
           
            //字符串等于空串自然也是: 空串  
         //为空串
    }else{
           
           
         //不为空串
    }
    
  • Space characters have length 1 and are distinguished from empty strings (empty strings).

  • The empty string is a Java object with its own string length (0) and content (empty).

Null串 (null)

  • String variables can also store a special value called null, which means that there is currently no object associated with the variable.

  • Check if a string is empty:

    If(str = null){
           
           
        //为空串
    }else{
           
           
        //不为空串
    }
    
  • Check that a string is neither null nor empty:

    //首先要检查str不为null,如果在一个null值上调用方法,会报错
    If(str!=null&&str.length()!=0){
           
            
      //该字符串不为null也不为空串
    }
    

Commonly used methods in String class (String API)

The String class in Java contains more than 50 methods. Here are some commonly used String class methods:

  • char charAt(int index)

    Returns the code unit at the specified location.

  • int codePointAt (int dex)

    Returns the code point starting at the specified position.

  • int offsetByCodePoints (int startIndex,int cpCount)

    Returns the code point index starting from the startIndex code point and cpCount code points later.

  • int compareTo (String other)

    In lexicographic order, if the string is before other, a negative number is returned; if the string is after other, a positive number is returned; if the two strings are equal, 0 is returned.

  • IntStream codePoints()

Return the code points of this string as a stream. Call toArray to put them in an array.

  • new String(int [] codePoints,int offset,int count)

Constructs a string from count code points in the array starting at offset.

  • boolean empty()

  • boolean blank()

Returns true if the string is empty or consists of spaces

  • boolean equals(Object other)

Returns true if the string is equal to other

  • boolean equalsIgnoreCase(Object other)

Returns true if the string is equal to other (ignoring case)

  • boolean startsWith(String prefix)

  • boolean endWith (String suffix)

Returns true if the string begins with prefix or ends with suffix or .

  • int indexOf (String str)

  • int indexOf (String str,int fromIndex)

  • int indexOf (int cp)

  • int indexOf (int cp,int fromIndex)

Returns the starting position of the first substring matching the string Str or the code point cp. Start matching from index 0 or fromIndex. If str does not exist in the original string, -1 is returned.

  • int lastIndexOf (String str)

  • int lastIndexOf (String str,int fromIndex)

  • int lastindexOf (int cp)

  • int lastindexOf (int cp,int fromIndex)

Returns the starting position of the last substring matching the string Str or the code point cp. Match starting from the end of the original string or fromIndex.

  • int length( )

Returns the number of string code units.

  • int codePointCount(int startIndex,int endIndex)

Returns the number of code points between startIndex and endIndex-1.

  • String replace (CharSequence oldString,CharSequence newString)

Returns a string that replaces all oldStrings in the original string with newStrings. You can use String or StringBuilder objects as CharSequence parameters.

  • String substring( int beginIndex)

Returns a string containing all characters from beginIndex to the end of the string.

  • String substring( int beginIndex,int endIndex)

Returns a string containing all characters from beginIndex to endIndex-1.

  • String toLowerCase( )

Change the uppercase letters in the original string to lowercase letters.

  • String toUpperCase( )

Change all lowercase characters in the original characters to uppercase characters.

  • String trim( )

  • String strip( )

This string will delete characters (trim) or spaces (strip) less than or equal to U+0020 from the head and tail of the original string.

  • String join(CharSequence delimiter ,CharSequence… elements)

Joins all elements with the given delimiter.

  • String repeat( int count)

Repeat/copy the current string count times.

View StringAPI documentation

  • API documents can be downloaded from Oracle and saved locally.
  • Also available in a browser: https://docs.oracle.com/javase/9/docs/api

Build string (StringBuffer):

Sometimes you need to build a string from a shorter string, such as keystrokes or words from a file. If string concatenation is used to achieve this purpose, the efficiency will be relatively low. Each time strings are spliced, a new String object will be constructed, which is time-consuming and space-consuming. This problem can be solved using StringBuilder.

Construct a string from many small string segments

		String ch = "Hello";
     String str = "World";
     String str2 = "...";

     //构建一个空的 字符串构建器
     StringBuilder builder = new StringBuilder();
     //当每次需要添加一部分内容时,就调用append方法
     builder.append(ch);
     builder.append(str);
     builder.append(str2);
//当字符串构建完成时就调用toString方法,将可以得到一个String对象,其中包含了构造器中的字符序列。
     String completeString = builder.toString(); //HelloWorld...

Important methods commonly used in the StringBuffer class:

  • StringBuilder( )

    Constructs an empty string constructor.

  • int length()

    Returns the number of code units in the constructor or buffer.

  • StringBuilder append(String str)

    Appends a string and returns this

  • StringBuilder append(char c)

    Appends a code unit and returns this

  • StringBuilder appendCodePoint(int cp)

    Appends a code point, converts it to one or two code units and returns this.

  • void setCharAt(int i,char c)

    Set the i-th code unit to c

  • StringBuilder insert(int offset .String str)

    Insert a string at offset position and return this

  • StringBuilder insert(int offset .char c)

    Inserts a word code unit at offset position and returns this

  • StringBuilder delete(int startIndex ,int endIndex)

    Delete the code unit with offset from startIndex to startIndex -1 and return this

  • String toString()

    Returns a string identical to the contents of the builder or buffer.

Guess you like

Origin blog.csdn.net/m0_70720417/article/details/132178934