Home > Java > javaTutorial > body text

[JAVA Example] String search, reverse, delete

黄舟
Release: 2017-02-07 10:49:20
Original
1206 people have browsed it

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);
      }
   }}
Copy after login

The output result of the above code example is:

Found Hello at index 0
Copy after login

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);
   }}
Copy after login

The output result of the above code example is:

String before reverse:abcdef
String after reverse:fedcba
Copy after login

▎ 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);
   }}
Copy after login

The output result of the above code example is:

thi is Java
Copy after login

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 (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!