Monday, December 13, 2010

Java Substring Compare Example

Welcome back to Java Code Online. Today's tutorial discusses comparison of a substring with other strings which is often required in Java programs.

In my last project I used to receive a large String message from a JMS sender via MQ. I was supposed to extract substrings from that original String using already known starting and ending index values. If the substring found matches the substring required, then the comparison is successful.

Today's example is based on the above process of comparison and matching the substrings.

Compare a substring
Task:- Extract a substring from a string starting at index value 5 and ending at index value 9. Compare it with the word "test", if a match occurs then display success else display no match.

The code is given below:-

    package JavaTest1;

    class TestIntToString {

        public static void main(String[] args) {

            String subStr = null;

            // Suppose this is the initial String,
            // we may also get this String from
            // the user or another external source
            String str = "I am testing substring comparision";

            // This is the word we are looking for in the
            // above string
            String strCompare = "test";

            // The starting Index value is
            int startIndexVal = 5;

            // The ending index value is
            int endIndexVal = 9;

            // Extract the substring in subStr
            subStr = str.substring(startIndexVal, endIndexVal);

            // Compare the subStr with strCompare
            if (subStr.equals(strCompare)) {
                System.out.println("Match Found in comparison, Success");
            } else {
                System.out.println("No Match found in comparison, Faliure");

When the above code is executed, the output is:-
      Match Found in comparison, Success

Related Articles
Search and Replace a Substring in Java Example

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.