Common instances and functions of Java strings

Source: Internet
Author: User

    • string comparison

String Functions CompareTo (String), Comparetoignorecase (String), and CompareTo (object string) to compare two strings and return the difference between the first letter of ASCII in a string.

 Public class stringcompareemp{   publicstaticvoid  main (String args[]) {      = " Hello World ";       = "Hello World";       = str;       System.out.println (Str.compareto (anotherstring));      System.out.println (Str.comparetoignorecase (anotherstring));   // Ignore Case       System.out.println (Str.compareto (objstr.tostring ()));}   }

    • String Lookup

The String class's IndexOf () method finds where a substring appears in a string, such as where the return string appears (the first bit is 0), and if no return-1 exists.

 Public class searchstringemp {   publicstaticvoid  main (string[] args) {      = " Google Java Taobao ";       int intindex = strorig.indexof ("Java");       if (Intindex = =-1) {         System.out.println ("string Java not Found");      } Else {         System.out.println ("Java string position" + intindex);    }}}

    • Find where the string last occurred

The String function Strorig.lastindexof (Stringname) to find the substring stringname where the strorig appears.

 Public class searchlaststring {   publicstaticvoid  main (string[] args) {      = " Hello World, Hello Runoob ";       int lastIndex = strorig.lastindexof ("Hello");       if (LastIndex = =-1) {         System.out.println ("string not Found");      } Else {         System.out.println ("where the string last appears:" + LastIndex);}}}   
    • Remove one character from a string

By using the String function substring () function to remove one character from a string, we encapsulate the function in the Removecharat function.

 Public class Main {   publicstaticvoid  main (String args[]) {      = ' This is Java ' ;       3));   }     Public Static int POS) {      return s.substring (0, POS) + s.substring (pos + 1);}   }

    • String substitution

The Replace method of the Java string class can replace characters in a string.

 Public class Test {    publicstaticvoid  Main (string args[]) {            string str= " Hello World,hello Java. " ;            System.out.println (str.replace (' H ', ' W ')); Replace All            System.out.println (Str.replacefirst ("He", "Wa"));//Replace the first encountered            System.out.println ( Str.replaceall ("He", "Ha")); Replace All       }}

    • String inversion

The inverse function of Java reverse () can be string reversed.

 Public class Test {    publicstaticvoid  Main (string args[]) {            string str= " Hello Java. " ;             New StringBuffer (str). reverse (). toString ();            System.out.println ("string reversal before:" +str);            System.out.println ("After string reversal:" +reverse);}       }

    • String segmentation

The split (string) method splits a string into an array by specifying a delimiter.

 Public classTest { Public Static voidMain (String args[]) {string str= "Www-baidu-com";            String[] temp; String Delimeter= "-";//Specify delimitertemp = Str.split (delimeter);//Split String//normal for Loop             for(inti = 0; i < temp.length; i++) {System.out.println (temp[i]); System.out.println (""); } System.out.println ("----java for Each loop output method-----"); String str1= "Www.baidu.com";            String[] Temp1; String Delimeter1= "\\.";//Specifies the delimiter, the. Number needs to be escapedTemp1 =Str1.split (Delimeter1);  for(String x:temp1) {System.out.println (x); System.out.println (""); }           }}
    • String lowercase to uppercase

The string toUpperCase () method converts the strings from lowercase to uppercase.

String str = "string Runoob";         = Str.touppercase ();

    • Tests whether two string regions are equal
 Public classstringregionmatch{ Public Static voidMain (string[] args) {String first_str= "Welcome to Microsoft"; String Second_str= "I work with Microsoft"; BooleanMatch1 =First_str. Regionmatches (One, Second_str, 12, 9); BooleanMATCH2 =First_str. Regionmatches (true, one, Second_str, 12, 9);//The first parameter, True, indicates that the case difference is ignoredSYSTEM.OUT.PRINTLN ("Case-sensitive return value:" +match1); System.out.println ("Case-insensitive return value:" +MATCH2); }}

first_str.regionmatches (One, Second_str, 9) indicates that the first_str string starts with the 11th character "M" and second_str The 12th character "M" of the string begins to be compared, comparing 9 pairs of characters, and the result is false because the string is case-sensitive.

If the first parameter is set to True, the case difference is ignored, so true is returned.

    • Connection string

Use the "+" operator and the Stringbuffer.append () method to concatenate strings.

 Public classStringconcatenate { Public Static voidMain (string[] args) {LongStartTime =System.currenttimemillis ();  for(inti=0;i<5000;i++) {String result= "This is" + "testing the" + "difference" + "between" + "String" + "and" + "StringBuffer"; }        LongEndTime =System.currenttimemillis (); System.out.println ("String Connection" + "-using the + operator:" + (Endtime-starttime) + "MS"); LongStartTime1 =System.currenttimemillis ();  for(inti=0;i<5000;i++) {stringbuffer result=NewStringBuffer (); Result.append ("This is"); Result.append ("Testing the"); Result.append ("Difference"); Result.append ("Between"); Result.append ("String"); Result.append ("and"); Result.append ("StringBuffer"); }        LongEndTime1 =System.currenttimemillis (); System.out.println ("String Connection" + "-using StringBuffer:" + (ENDTIME1-STARTTIME1) + "MS"); }}

Output:
String connection-using the + operator:0-using stringbuffer:42 ms

Common instances and functions of Java strings

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.