Java String trim() method

Java String Trim

Well, with this method, we can cut down the spaces before and after the string. Let’s discuss a problem where you might want to use this method. Just consider that you are writing a program where you are taking a user input string, and if the user inputs hi, you output as hello, and if the user inputs bye, you output something like ok… bye-bye.

This is kind of a pretty simple program, but it gets important when it comes to user input.

Here is a sample program for doing the same –

import java.util.Scanner;
public class StringMethods {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“Say hi or bye”);
String str1 = scanner.nextLine();
if (str1.equals(“hi”)){
System.out.println(“Hello”);
}
else if(str1.equals(“bye”)){
System.out.println(“Ok… Bye”);
}
else{
System.out.println(“Sorry… Not recognized…”);
}
}
}

This code looks and works fine, but it won’t work fine in every case. One thing is that if the user input does not match the case, or if I try adding some spaces before and after the input, like this – ” hi ”, it says not recognized. But we did the input as hi, so what is wrong now? Well, the wrong is in the spaces here. One more thing is that we have to take care of the case too. It is like the user inputs Hi, and the program compares it with hi, and then is going to give false only. So it is better to convert the input into complete lowercase, or uppercase as you like(or even you can use the equalsIgnoreCase method). This is because once the user inputs are done, you have the flexibility to do the things. See this program, which corrects the small bugs related to spaces and the cases.

import java.util.Scanner;
public class StringMethods {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“Say hi or bye”);
String str1 = scanner.nextLine().trim().toLowerCase(); // trim the spaces, and convert to lowercase…!
if (str1.equals(“hi”)){
System.out.println(“Hello”);
}
else if(str1.equals(“bye”)){
System.out.println(“Ok… Bye”);
}
else{
System.out.println(“Sorry… Not recognized…”);
}
}
}

So, executing this program, if the user inputs are somewhat different, like having spaces, or not having proper cases, they can be still handled here. Notice that in the above program, to compare the strings, we made the user of equals method. To handle the conflicts of cases, we can also use equalsIgnoreCase() to ignore the cases while we are comparing the string contents. Then in this case there wont is any need to call the toLowerCase() method. You can try doing this, while we move ahead.