Java Example - String Search
The following example uses the indexOf() method of the String class to find the position where the substring appears in the string. If it exists, return the position where the string appears (the first bit is 0), if it does not exist, it returns -1:
//SearchStringEmp.java 文件public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1){ System.out.println("Hello not found"); }else{ System.out.println("Found Hello at index " + intIndex); } }}
The output result of the above code example is:
Found Hello at index 0
String reversal
The following example demonstrates how to use Java The reverse function reverse() reverses the string:
public class StringReverseExample{ public static void main(String[] args){ String string="abcdef"; String reverse = new StringBuffer(string). reverse().toString(); System.out.println("nString before reverse: "+string); System.out.println("String after reverse: "+reverse); }}
The output result of the above code example is:
String before reverse:abcdef String after reverse:fedcba
▎ Delete a character in the string
In the following example, we use the string function substring() function to delete a character in the string, and we encapsulate the function in the removeCharAt function.
The example code is as follows:
//Main.java 文件public class Main { public static void main(String args[]) { String str = "this is Java"; System.out.println(removeCharAt(str, 3)); } public static String removeCharAt(String s, int pos) { return s.substring(0, pos) + s.substring(pos + 1); }}
The output result of the above code example is:
thi is Java
The above is the content of [JAVA example] string search, reversal, and deletion, and more For related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!