当前位置:网站首页>Basic part: string operation

Basic part: string operation

2021-06-23 22:35:38 cscw

Preface

Common operation of string , Remember . If you have string manipulation tips , Easy to use tool class , Welcome to complete . Please feel free to like it , Take a look

  • String Realization principle
  • String Common methods
  • The string cache pool and String.intern
  • Regular matching and strings
  • StringBuffer and StringBuilder
  • spring Tool class StringUtils

Official account , Communicate together , Search on wechat : Sneak forward

github Address , thank star

String Realization principle

public final class String implements Serializable,Comparable<String>, CharSequence {
    private final char value[];
    private int hash; // Default to 0

String There is one value Array of characters , Used to hold strings . The default encoding is utf-8

String Common methods

// from toffset Start , Whether or not to prefix start 
public boolean startsWith(String prefix, int toffset)
//str The last subscript that appears 
public int lastIndexOf(String str)
// Return subscript in beginIndex and endIndex String between 
public String substring(int beginIndex, int endIndex)
// Connect str, And return a new string 
public String concat(String str)
// matching regex Regular expressions 
public boolean matches(String regex) 
// Replace character 
public String replace(char oldChar, char newChar)
// Replace string 
public String replace(CharSequence target, CharSequence replacement)
// obtain charsetName Encoded byte array 
public byte[] getBytes(String charsetName)
// obtain 
public int codePointAt(int index)
// Division 
public String[] split(String regex, int limit)
// Converted to lowercase 
public String toLowerCase()
// Capitalize 
public String toUpperCase() 
// Take the space before and after 
public String trim()
//elements Use delimiter As a connector , Merge into a new string 
public static String join(CharSequence delimiter, CharSequence... elements)   
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
//args Parameters are filled in format Placeholder for , And return the new string 
public static String format(String format, Object... args)
// String converted to cache pool 
public native String intern()

Examples of use

String data = "String String manipulation - Must know must have ";
System.out.println(data.startsWith("St",0));
System.out.println(data.startsWith("St",5));
----------
true
false

Formatted output of string

public static String format(String format, Object... args)

System.out.println(String.format("%s-%s","wst","csc"));
--------
wst-csc

The string cache pool and String.intern

string.intern();intern First determine whether the constant pool stores the same string , If it exists, the reference is returned ; Otherwise, the reference to the string first appears in the record heap in the constant pool , And return the reference .

If it is executed first String s = "st" ; It's equivalent to executing intern(); First create... In the constant pool "st", And will quote A Into the constant pool , Return to s. here String("hello").intern() Returns a reference to the constant pool A return

Examples of use

public static void main(String[] args) throws Exception {
        String one = "st";
        String two = new String("st");
        String three = two.intern();
        System.out.println(two == one);
        System.out.println(three == one);
    }
---------------
false
true

String and regular matching 、Matcher

character explain
\ Mark the next character as a special character 、 Text 、 Reverse reference or octal escape character . for example ,"n" Matching character "n"."\n" Match newline ,"\(" matching "("
^ Matches where the input string starts . If set RegExp Object's Multiline attribute ,^ Also with "\n" or "\r" Position matching after
$ Matches the position of the end of the input string . If set RegExp Object's Multiline attribute ,$ Also with "\n" or "\r" Previous position match
* Zero or more matches the preceding character or subexpression . for example ,zo matching "z" and "zoo". Equivalent to {0,}
+ Matches the preceding character or subexpression one or more times . for example ,"zo+" And "zo" and "zoo" matching , But with "z" Mismatch .+ Equivalent to {1,}
? Matches the preceding character or subexpression zero or once . for example ,"do(es)?" matching "do" or "does" Medium "do".? Equivalent to {0,1}
{n} n Is a nonnegative integer . Just match n Time . for example ,"o{2}" And "Bob" Medium "o" Mismatch , But with "food" Two of them "o" matching
{n,} n Is a nonnegative integer . Match at least n Time . for example ,"o{2,}" Mismatch "Bob" Medium "o", Matching "foooood" All in o."o{1,}" Equivalent to "o+"."o{0,}" Equivalent to "o*"
{n,m} m and n Is a nonnegative integer , among n <= m. Match at least n Time , at most m Time . for example ,"o{1,3}" matching "fooooood" First three in o.'o{0,1}' Equivalent to 'o?'. Be careful : You cannot insert spaces between commas and numbers .
? When this character follows any other qualifier (*、+、?、{n}、{n,}、{n,m}) Later on , The matching pattern is " Non greedy "." Non greedy " Pattern matching found 、 The shortest possible string , And the default. " Greedy " Pattern matching found 、 String as long as possible . for example , In string "oooo" in ,"o+?" Match single "o", and "o+" Match all "o".
. Matching elimination "\r\n" Any single character other than . To match include "\r\n" Any character in , Please use such as "[\s\S]" Patterns like that .
\n Newline match . Equivalent to \x0a and \cJ
\r Match a carriage return . Equivalent to \x0d and \cM
\s Matches any whitespace characters , Including Spaces 、 tabs 、 Form-feed character, etc
\d Number character matching . Equivalent to [0-9]
[a-z] character in range . Matches any character in the specified range . for example ,"[a-z]" matching "a" To "z" Any lowercase letter in the range

Examples of use

public static void main(String[] args) throws Exception {
        String content = "I am st ! ";
        String pattern = ".*st.*";
        boolean isMatch = Pattern.matches(pattern, content);
        System.out.println(" Does the string contain  'st'  Substring ? " + isMatch);
    }
---------------
 Does the string contain  'st'  Substring ? true

StringBuffer and StringBuilder

StringBuffer、StringBuilder and String equally , Also used to represent strings .String Class is immutable , Re apply for memory every time , however StringBuffer and StringBuilder Is to apply for cache memory in advance , When splicing long and long strings , Performance ratio String good

StringBuffer It's thread safe , Every addition and subtraction is locked ;StringBuilder It is StringBuffer No lock version . If you don't know about thread safety , It is recommended to use StringBuffer, There is no need to consider the performance loss caused by locking , because jvm It will be automatically optimized to lock free operation according to the situation

spring Tool class StringUtils

public static boolean isEmpty(Object str)
// Whether there are spaces 
public static boolean containsWhitespace(CharSequence str) 
// Intercept the spaces on both sides 
public static String trimWhitespace(String str)
// Replace all spaces 
public static String trimAllWhitespace(String str)
// Get the file name 
public static String getFilename(String path)

Welcome refers to a mistake in the text

Reference article

版权声明
本文为[cscw]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/06/20210623223437212P.html