HomeJava

String manipulation in Java with examples

String manipulation in Java with examples
Like Tweet Pin it Share Share Email

Any programming language including Java uses variables to store data. When it comes to Java, being an object oriented programming language it has separate class for each data type. One such class is “String” it comes with set of methods by default. String manipulation in Java is more easy with the set of methods it has and it is crucial for test automation, we will discuss about them in this article.

Some of the important methods that you need learn are as follows

  • split
  • replace
  • replaceAll
  • contains
  • substring
  • indexOf
  • lastIndexOf
  • equals
  • equalsIgnoreCase
  • endsWith
  • startsWith
  • length
  • toUpperCase
  • toLowerCase
  • isEmpty

Some of the use cases where string manipulation needed in test automation are as follows:

Use cases in test automation which needs String manipulation in Java
Use case 1: Extract number from a given string.
Example: A success message is displayed on a web application saying “Your order number 32453 is generated successfully”, we need to extract the number from this string and later use to search the order and track the order status or may be any other purposes.
Use case 2: Verify if a desired text is present in a paragraph of content. 
Example: Each product in a shopping cart website displays set of the features in a product description. If the script need to verify whether a certain set of “SEO” keywords are available or not.
Use case 3: Verify if expected and actual value on application are matching or not
Example: As part of test automation, it is very common to verify if an appropriate error or success message is displayed on the application or not. Test automation script captures the text from the application and it tries to compare with the expected value, it helps to report whether the verification had actually passed or failed.

 

Methods with examples
Method:Split
Purpose: It is generally used to slice the given string in to multiple strings, this function takes delimiter as an input and returns an array of Strings
Code:

public class StringMan
{

    public int wordCount(String input)
    {
        // splitting a given string with a space will
        // return number of words
        String[] ips = input.split(" ");
       // length of this array gives us
       // number of words in the actual
       // string
        return ips.length
    }

    public static void main(String rs[])
    {
        StringMan sm = new StringMan();
        String test = "This is an example for split method in String class";
        int count = sm.wordCount(test);

        System.out.println("Number of words in test string are:" + count);
    }

}

Output: Number of words in test string are: 10

Method: replace
Purpose: When you want to replace a certain part of the string with another string, you can use this method. Takes two parameters as input and returns a string back. Parameter 1 is the sub string that you want to replace in the given input string, Parameter 2 is the new sub string that you want to have in the given input string post replacing the old sub string.
Code:

public class StringMan
{
    public static void main(String rs[])
    {
        String description = "This tutorial is part of C programming language.");
        // String "C" is replaced with "Java"
        // in above string. 
        // also remember that you need to 
        // assign it to a string variable
        description = description.replace("C","Java");
        System.out.println(description);
    }

}

Output: This tutorial is part of Java programming language.

Method: contains
Purpose: When you want to replace a certain part of the string with another string, you can use this method. Takes two parameters as input and returns a string back. Parameter 1 is the sub string that you want to replace in the given input string, Parameter 2 is the new sub string that you want to have in the given input string post replacing the old sub string.
Code:

public class StringMan
{
    public static void main(String rs[])
    {
        String description = "This tutorial is part of C programming language.");
        // in the below statement 
        // "contains" method checks if
        // tutorial string is present
        // in the given string
        if(description.contains("tutorial"))
        {
            System.out.println("Tutorial is present in the given string.");
        }
        else
        {
            System.out.println("Tutorial is not present in the given string.");
        }
        System.out.println(description);
    }

}

Output: Tutorial is present in the given string

code in the true section of if condition is executed as “tutorial” is present in the given string.

Method: equals
Purpose: This method “equals” can help you check if the current string is equal to the given input string. It returns a boolean value stating if its equal or not. Equals method will not work for the strings if they are not matching the case for each character in the strings, you can use an alternative method called equalsIgnoreCase.

public class StringMan
{
    public static void main(String rs[])
    {
        String language = "Java";
        // below statement checks if
        // variable language is equal 
        // to Java. 
        if(language.equals("Java"))
        {
            System.out.println("Java is a programming language.");
        }
        else if(language.equals("C"))
        {
            System.out.println("C is a procedural programming language");
        }
        else
        {
            System.out.println("Doesn't match any programming language");
        }
    }

}

Output: Java is a programming language.

code in the first if condition is executed as value of both string variable language and first condition is “Java”.  They even match with right case ( lower case and upper case of each character in the string )

Some of the methods are explained here, remaining methods from the above mentioned list are quite self explanatory as what they are intended for.  You can use them only once you are aware of the syntax, input parameters and  what the method returns. You can learn more details at Java API’s documentation for String class. You can also witness more methods to what are mentioned above in this article.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *