Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

In Java How to Get all Text After Special Character from String?

In Java How to Get all Text After Special Character from String?

Java substring() utility is a very powerful library if you want to perform multiple special operations on String.

It simply returns a substring of the specific string based on number of operations like indexOf() or lastIndexOf().

In this tutorial we will go ver very simple example of grabbing everything after special character _ and *.

Just open your Eclipse IDE, copy below code and try running as Java Application.

CrunchifyGetStringAfterChar.java

package crunchify.com.java.tutorials;

/**
 * @author Crunchify.com
 * Program: Get everything after Special character like _ or : or * from String in java
 *
 */

public class CrunchifyGetStringAfterChar {

    public static void main(String[] args) {

        String crunchifyStr = "Hey.. This is Crunchify.com";
        String crunchifyStr2 = "HELLO_THIS_IS_CRUNCHIFY_COM";
        String crunchifyStr3 = "This is simple substring example *";

        // substring(): Returns a string that is a substring of this string.
        // The substring begins with the character at the specified index and extends to the end of this string.
        crunchifyLog(crunchifyStr.substring(crunchifyStr.indexOf(".") + 2));

        // indexOf(): Returns the index within this string of the first occurrence of the specified substring.
        crunchifyLog(crunchifyStr2.substring(crunchifyStr2.indexOf("_") + 1));

        // lastIndexOf(): Returns the index within this string of the last occurrence of the specified substring.
        // The last occurrence of the empty string "" is considered to occur at the index value this.length().
        crunchifyLog(crunchifyStr3.lastIndexOf("*") + "");

        crunchifyLog(crunchifyStr2.indexOf("_") + "");
    }

    private static void crunchifyLog(String string) {
        System.out.println(string);

    }
}

IntelliJ IDEA Console output:

Just run above program as a Java program and you will see result as below.

This is Crunchify.com
THIS_IS_CRUNCHIFY_COM
33
5

Let me know if you prefer to perform the same action using Apache Commons library.

I personally think, it’s not required to add extra dependency just for this.

The post In Java How to Get all Text After Special Character from String? appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires