JAVA learning lesson 30th (Common Object API)-String class: Class Method exercises
Intern Method
Public class Main {public static void main (String [] args) {String str1 = new String ("asd"); String str2 = str1.intern ();/* The String constant pool has, returns the string. If no string is returned, the System creates */System. out. println (str2); System. out. println (str1 = str2 );}}
Exercise 1: Sort string Arrays
Import java. util. substring;/** specify a String array in ascending Lexicographic Order */public class Main {public static void main (String [] args) {stringsort ();} public static void stringsort () {String [] str = new String [10]; exist in = new expect (System. in); for (int I = 0; I <str. length; I ++) {str [I] = in. nextLine ();} // System. out. println (str. length); for (int I = 0; I <str. length-1; I ++) {for (int j = 0; j <str. length-1-I; j ++) {if (str [j]. compareTo (str [j + 1])> 0) {String t = str [j]; str [j] = str [j + 1]; str [j + 1] = t ;}}for (String iString: str) {System. out. println (iString );}}}
Exercise 2: count the number of times the substring appears in the parent string
IndexOf application, record the current subscript A, and then continue from the length of A + substring after indexOf, Use loop to achieve this function
Import java. util. counts;/** number of times a substring appears in a String */public class Main {public static void main (String [] args) {count ();} public static void count () {String str = "abcdefabcghiabcsdabchzabc"; int num = 0, wz = 0; for (int I = 0; I <str. length (); I ++) {int t = str. indexOf ("abc", wz); if (t! =-1) {wz = t + "abc". length (); num ++;} else break;} System. out. println (num );}}
Exercise 3: Maximum and same substrings of two strings
Import java. util. longest;/** the longest public substring */public class Main {public static void main (String [] args) {String tString = compare (); System. out. println (tString);} public static String compare () {String str1 = "vbabcdefgsdfg"; String str2 = "asdabcdefgdf"; int Mlen = str1.length (); int Zlen = str2.length (); int len = (Mlen> Zlen )? Zlen: Mlen; // find a shorter parent string. The maximum public length cannot exceed len // The Public substring may appear in the middle for (int I = 0; I <len; I ++) // control the maximum length {for (int j = 0, k = len-I; k <= len; k ++, j ++) // j controls several conditions, and k controls the substring's final element subscript not to cross-border {String sub = str2.substring (j, k); if (str1.contains (sub) return sub ;}} return null ;}}
Exercise 4: Remove spaces at both ends (trim simulation)
public class Main {public static void main(String[] args) {String string = " asd fs fg h ";int st = 0,en = string.length()-1;for(;st<=en && string.charAt(st)==' '; st++);for(;st<=en && string.charAt(en)==' '; en--);String sub = string.substring(st, en+1);System.out.println(sub);}}