How to trim extra spaces from the string using a Java
We are initializing a public class in which all the code will be written as shown below:
………
}
For this example, in the main function, we have defined some text in java with some extra spaces that we are going to trim in the later code.
If you want to find the total length of the string then you can do that by typing:
Now we are going to display the string along with its length as shown below
There is a built-in trim() function in Java that can be used to trim the unnecessary space from the string and for our code, we can use that by typing:
In the above code the string is stored in the ‘str1’ variable so we are going to trim that by typing str1.trim() and then saving the result in the new variable which is ‘str2’. Now after trimming we are also going to find the new length of the string and for that, we have used str2.length() function and save the result inside an ‘n’ variable. After that, we are also going to display the new result on the screen using System.out.println() function:
The complete code is:
public static void main(String[] args) {
System.out.println("String trim Example \n");
//Declare a string
String str1 =" This string contains extra spaces. ";
int n=str1.length(); //This line returns the length of string to variable n
System.out.println("String: "+ str1);
System.out.println("Length: "+ n);
String str2=str1.trim();
n=str2.length();
System.out.println("After trimming, String: "+ str2 );
System.out.println("Length of the trimmed string: "+ n);
//All white spaces like space character, new line character (\n), tab (\t)
//that are present at the start or at the end of the string are removed.
}
}
Terminal in Linux operating system provides the simplest way to implement and execute the code using a java programming language. First, you need to create a java file using a terminal by typing:
The next step is to write and save the code in the Java file:
Note: You need to install the java development kit (JDK) application to execute the java based programs by typing:
After saving the file you need to compile it first and then you can execute it by typing:
$ java StringTrim
Conclusion
String trim is a built-in function that is available in the Java library used to remove the extra space from the string. To make strings more clear and concise, you can use a Java built-in function with a name of trim() that we have explained in this article. This article is a detailed guide on how to use Java Trim() function to modify strings.