Java Learning string

Source: Internet
Author: User

A, String

As for the string variable, we must know that the string is not the base data type, but an object, the string object is an immutable object, once created in memory, the content cannot be changed, and to change the contents of the string, a new object is created.

When creating a String object, we know that the value is null before initialization.

string S1 =nullnew String ();

S2 represents an object that has not yet been created, so that its memory has not been allocated

S1,S3 means there is memory space, but there is no value in the space

  String Common methods:

Equals ()--Determines whether the content is the same.

CompareTo ()--Determines the size relationship of the string.

Comparetoignorecase (String int)--ignores the case of letters when compared.

Equalsignorecase ()--Determines whether the content is the same if the case is ignored.

Reagionmatches ()--comparison of whether parts of a string are identical

charAt (int index)--Returns the character at the index position of the specified indices, starting at 0.

IndexOf (String str)--Retrieves the STR from the string and returns the position where it first occurred without returning-1.

IndexOf (string Str,int fromIndex);--retrieves str from the first fromIndex character of the string.

LastIndexOf (String str)--finds the last occurrence of the position.

LastIndexOf (String Str,int fromIndex)-finds the last occurrence from the first fromIndex character of a string.

Starwith (String Prefix,int toffset)-tests whether the substring starting at the specified index begins with the specified prefix.

Tarwith (string prefix)--tests whether this string starts with the specified prefix.

EndsWith (string suffix)--tests whether this string ends with the specified suffix.

public string subString (int beginindex)--Returns a new string that is a substring of this string.

public string subString (int beginindex,int endIndex)-The string returned is from Beginindex to endIndex-1.

Public String replace (char Oldchar,char Newchar).

Public String replace (charsequence target,charsequence replacement)-Replaces the original Etarget subsequence with the replacement sequence and returns a new string.

public string ReplaceAll (string regex,string replacement)-implements a match to a string with a regular expression.

Second, Stringbuilder/stringbuffer

StringBuffer is thread-safe, synchronously processed, with slightly slower performance

StringBuilder is non-thread-safe, concurrently processed, with slightly faster performance (recommended)

Third, string test

  

/*** The String object in Java is an immutable object, meaning that after the creation of the string object, the content cannot be changed, and the new object must be created if you want to change the content. * Java uses a string constant pool to cache string objects created by literal literals and reuse them. * @authorAdministrator **/ Public classStringDemo1 { Public Static voidMain (string[] args) {String S1= "Hello"; String S2= "World"; String S3= S1 +S2; String S4= "HelloWorld"; String S5= "Hello"; System.out.println (S1==S5); System.out.println (S3==S4);                System.out.println (S3.equals (S4)); S4+= "!"; System.out.println (S3==S4); }}
 Public classStringDemo2 { Public Static voidMain (string[] args) {/** Compiler has an optimization measure, when compiling the source program, the computed expression is that both sides of the content is literal * Then it is calculated directly, and the results are compiled into a bytecode file * The advantage is that the JVM runs without having to calculate every time. * So the following code in the bytecode file is * String = "123ABC"*/String S1= "123ABC"; String S2= "123ABC"; String S3= "123" + "ABC"; String S4= "123"; String S5= S4 + "ABC"; String S6= 1 + "+" + "abc"; String S7= 1 + ' 2 ' + "3ABC";//53ABCString s8 = "33ABC"; String S9=NewString ("123abc"); System.out.println (S1==S9);                System.out.println (S7); System.out.println (S1==S3); System.out.println (S1==S5); System.out.println (S1==S6); System.out.println (S1==S7); }}
 Public classStringDemo3 {/*** int Length () * Returns the number of characters in the current string*/@Test Public voidtestlength () {String s= "HelloWorld"; intLen =s.length ();    System.out.println (len); } @Test Public voidTestindexof () {String s= "HelloWorld"; /** int indexOf (string str) * View the position of the given string in the current string, if any, returns the subscript position of the first character of the given string in the current string.         * If not, return-1. *          */        intindex = S.indexof ("L"); System.out.println ("Index:" +index); Index= S.indexof ("L"); System.out.println ("Index:" +index); /** Overloaded Method: You can find from a given position, the first time to display the position of a given string*/Index= S.indexof ("L", 3); System.out.println ("Index:" +index); /** int lastIndexOf (string str) * See where the given string last appeared in the current string*/Index= S.lastindexof ("L"); System.out.println ("LastIndex:" +index); } @Test Public voidtestsubstring () {/** string substring (int start,int end) * Intercept String * * Java API usually uses 2 numbers to denote the range, all with the head does not contain the tail         。 * below: Contains the corresponding characters for subscript 5, but does not contain 8 corresponding characters*/String S= "HelloWorld"; String Sub= S.substring (5, 8);//open front, including 5, not including 8 new stringSystem.out.println (sub); /** Overloaded Method: * string substring (int start) * is truncated to the end of the string at the beginning of the given position*/Sub= S.substring (4);    System.out.println (sub); }        /** Get the domain name * The first character after the first "." begins to intercept the string before the second ".". */@Test Public voidtestyuming () {String URL= "Www.baidu.com/?video.video"; intStart = Url.indexof (".") + 1;//first time position//int end = Url.lastindexof (".");        intEnd = Url.indexof (".", start);//Second positionString yuming =url.substring (start, end);    System.out.println (yuming); } @Test Public voidTesttrim () {String str= "Hello World"; /** String Trim () * Removes whitespace on both sides of the current string*/String Trim=Str.trim ();        System.out.println (str);    System.out.println (Trim); } @Test Public voidTestcharat () {/** Char charAt (int index) * View the characters at the given position in the current string*/String str= "HelloWorld"; CharCharAt = Str.charat (5);//look at the character labeled 5? That is, the sixth characterSystem.out.println (charAt); } @Test Public voidstartsandendswidth () {/** Boolean startsWith (String str) * Determines whether the current string starts with the given string * Boolean EndsWith (str ing str) * Determines whether the current string ends with the given string*/String str= "Hello World"; BooleanBOOL = Str.startswith ("Hello"); System.out.println ("Start with Hello:" +bool); BOOL= Str.startswith ("he");                SYSTEM.OUT.PRINTLN (BOOL); BOOL= Str.endswith ("World"); System.out.println ("Start with World:" +bool); BOOL= Str.endswith ("LD");    SYSTEM.OUT.PRINTLN (BOOL); } @Test Public voidtesttouppercaseandtolowercase () {/** String toLowerCase () * Converts the English part of the current string to full lowercase * * string touppercase () * Converts the English part of the current string to full capitalization*/String str= "Hello HelloWorld"; String ToLower=str.tolowercase ();                System.out.println (ToLower); String ToUpper=str.touppercase ();        System.out.println (ToUpper); /** This method is often used to ignore case of string validation on*/} @Test Public voidtestvalueof () {/** static string ValueOf () * This method uses several overloads to convert other types to strings*/        inti = 123; String iStr=string.valueof (i); IStr+ = 4;                System.out.println (ISTR); DoubleD = 123.456; String Dstr=string.valueof (d);                System.out.println (DSTR); System.out.println (String.valueof (true)); Char[] C =New Char[]{' A ', ' B ', ' C ', ' d ', ' e '}; String cStr=string.valueof (c);    System.out.println (CSTR); }    }

Four, Stringbuilder/stringbuffer test

/*** StringBuilder * It maintains a variable array of characters internally, which is used to modify the string using *@authorAdministrator **/ Public classStringbuilderdemo {@Test Public voidtesttostring () {StringBuilder sb=NewStringBuilder (); StringBuilder SB1=NewStringBuilder ("HelloWorld"); //Create a StringBuilder to modify the stringStringBuilder Strbu =NewStringBuilder ("Learning Java"); String Str= Strbu.tostring ();//to get the internal representation of a string by calling the ToString methodSystem.out.println (str); } @Test Public voidTeststringbuildermothod () {/** StringBuilder Append (string str) * Append the contents of the given string to the end of the current string * The return value is the current StringBuilder object, which is this * This is done for continuous editing operations*/StringBuilder SB=NewStringBuilder ("Learning Java");        System.out.println (Sb.tostring ()); Sb.append ("Win ... ");//sb.append ("");System.out.println (sb.tostring ()); Sb.replace (8, Sb.length (), "Changing the World");//ReplaceSystem.out.println (sb.tostring ()); Sb.delete (0, 8);//the string to delete which intervalSystem.out.println (sb.tostring ()); Sb.insert (0, "alive");//Where to insert what stringSystem.out.println (sb.tostring ()); Sb.reverse ();//Invert stringSystem.out.println (sb.tostring ()); }}

Java Learning string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.