Remove space from string Java
In this post, you will learn how to remove spaces from a string using Java programming. In the development process, sometimes we want to remove all occurrences of white-spaces from a string. There are different ways to remove spaces from a string in Java. Here, we have mentioned most of them -
Using replaceAll() function
The Java String class replaceAll() method returns a string replacing all the sequence of matched characters regex with a new character. It takes regular expression as input to identify the target substring that needs to be replaced.
Syntaxpublic String replaceAll(String regex, String replacement)
Here, we need to provide correct regular expression with correct replacement parameter. For example, if we want to find all spaces, the regular expression will be \s+
Java program to remove all spaces from string using built-in method
In the given example, we have removed the white spaces from the string using Java built-in method.
// Java remove whitespaces
// using built in method
public class RemoveSpace {
public static void main(String[] args)
{
String str = " Welcome to etutorialspoint . ";
System.out.println("Original String: " + str);
// Calling the replaceAll() method
str = str.replaceAll("\\s", "");
System.out.println("New String: " + str);
}
}
Output of the above code:
Original String: Welcome to etutorialspoint .
New String: Welcometoetutorialspoint.
Java program to remove all spaces from string
In this given example, we have written code to remove all spaces from string using the forloop and stringBuffer() method.
// Java remove whitespaces
// using built in method
public class RemoveSpace {
public static void main(String[] args)
{
String str = " Welcome to etutorialspoint . ";
System.out.println("Original String: " + str);
char[] strArray = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < strArray.length; i++) {
if ((strArray[i] != ' ') && (strArray[i] != '\t')) {
stringBuffer.append(strArray[i]);
}
}
String newString = stringBuffer.toString();
System.out.println("New String: " + newString);
}
}
Output of the above code:
Original String: Welcome to etutorialspoint .
New String: Welcometoetutorialspoint.
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number