Java from entry to the master string Chapter 5

table of Contents

Creating strings

Connection String

Gets a string of information 

String Manipulation

Format string

Using regular expressions

String generator

Exercise


Creating strings

  • Quoted string constant
    • String a; a = "student";
    • Use the same string constants assigned to different variables, their addresses are the same (a == b), the program will look for it exists or not constant in the stack, there is a direct address assigned to a new variable instead of re-heap create objects
  • Using the constructor
    • String a = new String("student")
    • String b = new String(a)
  • Examples of the use of an array of characters
    • String a = new String(char a[])
    • String a = new String(char a[], int offset, int length)
  • Examples of using the byte array
    • String a = new String(byte a[])

Connection String

  • Connecting the plurality of strings
    • +
    • + Time = variable name is very long, high readability
  • Other types of connection
    • + Operator has only one operand is a string, the compiler will convert the other operand to a string (automatically call toString () method)

Gets a string of information 

  • Get string length
    • str.length()
    • str.lastIndexOf ( ""); an empty string in a string index is equal to the length of the string
  • String search
    • str.indexOf (String s); s returns the index of the first occurrence of the specified string, not retrieved -1
    • str.indexOf(String s, int fromIndex);
    • str.lastIndexOf (String s); s return to the last location of the search string appears, not retrieved -1
    • str.lastIndexOf(String s, int fromIndex);
  • Gets the index position of the character
    • str.charAt(int index)

String Manipulation

  • Get a substring
    • str.substring (int beginIndex); return carriers from index position to the end of the string
    • str.substring (int beginIndex, int endIndex); return from the start to the end of the index sub-string of length endIndex - beginIndex, the last character index is not included within the meaning of
  • Remove the spaces before and after the string
    • str.trim();
  • String replacement
    • str.replace (char oldChar, char newChar); replacement character or string, no return to the original string
    • str.replaceAll ( "\\ s", ""); remove all spaces, the former is a regular expression parameter, the parameter is Replaced
  • Analyzing beginning and end of the string
    • str.startsWith (String prefix); return value boolean type
    • str.endsWith(String suffix);
  • Analyzing the strings are equal
    • str.equals (String otherstr);, returns a boolean value
    • str.equalsIgnoreCase (String otherstr); ignore case
  • Compare strings lexicographically
    • str.compareTo (String otherstr); compares successive string of characters, str if after otherstr, returns a negative integer before, after returning a positive integer, the return value before or after the first few positions. Equal return 0
    • str.compareToIgnoreCase(String otherstr);
  • Letter case conversion
    • str.toLowerCase();
    • str.toUpperCase (); non-numeric character is not affected
  • String split
    • str.split (String sign); sign is a separator, "|" is the definition of a plurality of separators, a regular expression may be
    • str.split (String sign, int limit); limit defines the number of divisions, the number is less than 0, dividing the whole greater than the maximum division number
    • split will match the regular expression. means match any character, you need to use \ to escape, and \ itself needs to be escaped so \\.

Format string

String class static method formate () is used to create formatted strings.

  • Date and time format string
    • Need to import import java.util.Date
    • Date date = new Date (); String s = String.formate (String form, date); s is the formatted string
  • Conventional type format

 

Using regular expressions

  • Regular expression metacharacters, this meta-character represents a specific set of characters
  • Square brackets [] enclosed element represents a character, the element can represent any character a character [abc] 4 a4 representative of the character element, b4, c4
    • [^ Abc] represents the character except abc, ^ represents the opposite
    • [Az] az represents any letter, - indicates a range
    • [Ae [gz]] [] was added [] represents arithmetic and
    • [Ao && [def]] && represents a cross-operation
    • [Ad && [^ bc]] && ^ represents the difference calculation binding
  • | Represents or, && represents a cross, [] represents any one of which, indicated to the contrary ^
  • Limited number modifier appears limited metacharacters
  • str.matchs (String regex); return boolean

String generator

String created using the string length is fixed which, when used for connecting a plurality of strings +, will produce a new String instance, create a new string object in memory, if duplicate modification of the string, will greatly increase system overhead. JDK5 new variable sequence of characters (String-Builder) class, which greatly improves the efficiency of the frequent increase in the string.

  • StringBuffer and StringBuider comparison:
    • To provide compatible API, but does not guarantee StringBuider thread synchronization, the disadvantage is only in a single thread, the advantage is not locked to the thread

  • StringBuffer, StringBuider, String interchangeable
    • String to convert or StringBuider use StringBuffer constructor new StringBuider (String) or new StringBuider (String)
    • StringBuffer, StringBuider converted into String using toString () method
    • StringBuffer and StringBuider conversion method to use toString () method to a String reuse constructor
  •  
  • StringBuilder builder = new StringBuider();
  • StringBuilder builder = new StringBuider("123");
  • StringBuilder builder = new StringBuider (32); an initial capacity of 32 characters
    • append (content); add content, StringBuider return object address
    • insert (int offset, arg); Inserts returns StringBuilder object
    • delete (int start, in end); deleted substring and returns the object StringBuider
    • setCharAt (int index, char ch); None Return Value
    • Reverse (); anti-order output;
    • toString (); return a String object
    • String and similar methods
      • int lengt = builder.length (); return string length
      • char chr = builder.charAt (int index); retrieve a specified index
      • int index = builder.indexOf (String str); Get index of the specified string
      • String substr = builder.substring (int beginIndex, int endIndex); get a substring
      • StringBuider tmp = builder.replace (int beginIndex, int endIndex, String str); replace the specified sequence of characters (with different String)
    • Other class methods of the API query java.lang.StringBuilder
    •  
  • StringBuffer buffer = new StringBuffer(); 同StringBuider
package ex5_String;

public class ex5_28_Jerque {
    public static void main(String[] args) {
        String str = "";
        long starTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            str += i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("time: " + (endTime - starTime));

        StringBuilder builder = new StringBuilder("");
        starTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            builder.append(i);
        }
        endTime = System.currentTimeMillis();
        System.out.println("time: " + (endTime - starTime));
    }
}

Exercise

  • Write the phone number of regular expressions
  • Use additional character string builder
package ex5_String;

public class ex5_practice_3 {
    public static void main(String[] args) {
        String text = "12345678912";
        String regex = "1\\d{10}";
        System.out.println(text + " is " + text.matches(regex) + " phone number");

        StringBuilder builder = new StringBuilder("");
        for (int i = 1; i<=10; i++) {
            builder.append(i);
        }
        System.out.println(builder.toString());
    }
}

 

 

 

 

 

 

 

 

Published 46 original articles · won praise 0 · Views 1034

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/103314197
Recommended