English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The String class represents strings. All string literals (such as "abc") in Java programs are implemented as instances of this class.
Strings are constants; their values cannot be changed after creation. String buffers support variable-length strings.
The methods included in the String class can be used to check a single character in a sequence, compare strings, search for strings, extract substrings,
Create a copy of the string and convert all characters to uppercase or lowercase.
The String class is one of the most commonly used classes. Below, through several exercises, we will become familiar with the important methods provided by the String class.
String Practice One
Given an array of strings, sort them in dictionary order, taking into account case sensitivity.
Approach:
1.To sort an array, selection sort, bubble sort, and so on can be used.
2.Nested for loops, comparisons, and swapping positions.
3.The difference is that previously, comparisons were made using numerical values and comparison operators;
Now we are comparing string objects, we should use the compareTo method.
public class StringTest_1 { //Sort the string array public static void stringSort(String[] arr) { //Use bubble sort for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i;j++) { //Use the compareTo method for string comparison if (arr[j].compareTo(arr[j+1]) > 0) { String temp = arr[j]; arr[j] = arr[j+1]; arr[j+1]=temp; } } } showArray(arr); } //Define a method to print the array in the format [str1, str2, str3"] "); public static void showArray(String[] arr) { System.out.print("[" for (int i = 0; i < arr.length; i++) { if (i != arr.length-1) System.out.print(arr[i+"," else { System.out.print(arr[i+"] "); } } } public static void main(String[] args) { String arr[] = {"nba", "abc", "cba", "zz", "qq", "haha"}; //Print the array showArray(arr); //Sort and output the array stringSort(arr); } }
Run:
String Exercise Two
The number of times a substring appears in a string
Approach:
1. Use the indexOf method to get the first occurrence position of the substring in the string index
2. Then use the indexOf method to get the position of the substring at (index+The position of the substring in the remaining string starting from the length of the substring) until the substring is no longer contained in the string. It can be implemented with a while loop.
3. Each time you find it, record it with a counter.
public class StringTest_2 { public static void main(String[] args) { String str = "abcqwabcedcxabcuabcjkabcnmbabc"; //String str = null; try { int count = countChildStr(str, "abc"); System.out.println("abc in"+str+The number of occurrences of "+count); } catch (NullPointerException ne) { System.out.println(ne); } catch (RuntimeException re) { System.out.println(re); } } public static int countChildStr(String str, String key) { if (str == null || key == null) { throw new NullPointerException("Null pointer exception, the source string and substring cannot be NULL"); } if (key == "") {throw new RuntimeException("Illegal call, substring must have content");} int count = 0, index = 0; while ((index = str.indexOf(key, index)) !=-1) { count++; index+= key.length(); } return count; } }
String exercise three
Find the maximum common substring of two strings
Approach:
1. Judge whether the longer string contains the shorter string. If it contains, the shorter string is the maximum common substring.
2. If it does not contain, take substrings of the shorter string in descending order of length, and judge whether it contains in the longer string. If it contains, it is found and no longer searched.
3. Key: Take substrings of the string in descending order of length
public class StringTest_3 { public static void main(String[] args) { //Create two non-empty strings String str1="abxczwsxcvdfas"; //String str1= null; String str2="ghwsxcvxcdbgthnnnrfqwe"; try { String str = searchMaxCommonStr(str1, str2); System.out.println("The maximum common substring is: "+str); } catch (NullPointerException ne) { System.out.println(ne); } } public static String searchMaxCommonStr(String str1, String str2) { if (str1== null || str2== null) throw new NullPointerException("Null pointer exception, parameter cannot be null"); //Determine the longer and shorter strings String max = (str1.length() > str2.length())? str1: str2; String min = (str1.equals(max))? str2: str1; //取子串,按长度递减的方式从min.length~~1 for (int i = min.length(); i > 0; i--) { for (int x = 0, y = x+i; y < min.length(); x++, y++) { String childStr = min.substring(x, y); //If the longer string contains this substring, then it is found //Otherwise, continue to find if(max.contains(childStr)) return childStr; } } return null; } }
Run:
String Practice Four
Write a method that is the same as the trim function
Approach:
1.Define two variables to store the two indices
2.Traverse the string from both the beginning and the end until the first non-space character is found
3.Trim the string
public class StringTest_4 { public static void main(String[] args) { String str=" abc ws "; str=myTrim(str); System.out.println(str); } public static String myTrim(String s) { int begin=0, end=s.length()-1; //Traverse from the beginning while(begin<=end && s.charAt(begin)==' ') { begin++; } //Traverse from the end while(begin<=end && s.charAt(end)==' ') { end--; } return s.substring(begin, end+1); } }
Run:
That's all for this article. I hope the content of this article can bring some help to everyone's learning or work, and I also hope to get more support for the Yelling Tutorial!
Statement: The content of this article is from the Internet, and the copyright is owned by the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @ when sending email) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.