Additional features of the String class:
Replacement function:
String replace (char Old,char new)
String Replace (string old,string new)
Remove string Two spaces
String Trim ()
Compare two strings in a dictionary order
int CompareTo (String str) Case-sensitive
int comparetoignorecase (String str) is case insensitive
1 Public classStringTest3 {2 3 Public Static voidMain (string[] args) {4String s = "HelloWorld";5 6 //character substitution: String replace (char Old,char new)7String S1 = s.replace (' o ', ' K ');8System.out.println (S1);//Hellkwkrld9 Ten //string Substitution: String replace (string old,string new) OneString s2 = s.replace ("ll", "KK"); ASYSTEM.OUT.PRINTLN (S2);//Hekkoworld - - the //Remove string Two spaces -String s4 = "Hello World"; -String S5 =S4.trim (); -System.out.println ("S4:" + S4 + "---");//the left and right spaces remain +System.out.println ("S5:" + S5 + "---");//the left and right spaces have been removed - + A //compare two strings in dictionary order (ASCII table): at //int compareTo (String str) -String A1 = "Cat"; -String A2 = "Dog"; -String a3 = "Cat"; -String a4 = "Door"; -String A5 = "Cat"; inString a6 = "C"; - to intI1 =A1.compareto (A2); + System.out.println (i1); - //-1 c in front of B, ASCII code table, A1 c minus A2 B, equals-1 the *System.out.println (A1.compareto (A3));// + $ //A1 C in ASCII value minus A2 C in ASCII value. GetPanax Notoginseng -System.out.println (A2.compareto (A4));//-8 the //A2 The first 2 letters do and A4 the first 2, a2 the third G minus A4 The third O, get-8 + ASystem.out.println (A1.compareto (A5));//0 the //A1 and A5 array elements are exactly the same + -System.out.println (A1.compareto (A6));//2 $ //Ctrl + Left click Comperto View Source $ } - - } the -CompareTo source code, as well as "System.out.println (A1.compareto (A6));//2 "AnalysisWuyi the Private Final Charvalue[]; - Wu the string is automatically converted to an array of characters. - About $ Public intcompareTo (String anotherstring) { - //this-a1-"Cat" - //anotherstring-a2-"C" - A intLen1 =value.length; + //this.value.length = A1.tochararray (). Length = = 3 the - intLen2 =anotherString.value.length; $ //anotherString.value.length = A2.tochararray (). length = = 1 the the intLim =math.min (Len1, len2); the //Lim = Math.min = 3-1 = 2; lim = 2 the - CharV1[] =value; in //char v1[] = {' C ', ' a ', ' t '}; the the CharV2[] =Anotherstring.value; About //char v2[] = {' C '}; the the intK = 0; the while(K <Lim) { + CharC1 = V1[k];//c1 = ' C ', ' a ', ' t ' - CharC2 = V2[k];//c2 = ' C ' the if(C1! =C2) {Bayi returnC1-C2; the } thek++;//when K=1, K!< lim, Lim = 1; so jump out of the loop - } - returnLen1-len2;//after jumping out of the loop, here, compare the lengths of two arrays 3-1 = 2 the } the theString A1 = "Cat"; theString a6 = "C"; -System.out.println (A1.compareto (A6));//2
Java11-6 other functions of the String class