Remove all whitespaces from String in Java
In programming, there are cases where we need to remove the whitespaces from the given string. Due to white space, we get unexpected results or exceptions.
There are many ways to remove whitespaces from String
1). Use String's replaceAll
2). Find and replace white Space
1). Use String's replaceAll
For removing all white spaces from String, use the replaceAll() method of String class.
package com.javacodestuffs.core.strings;
public class HelloWorld {
public static void main(String[] args) {
String str = " Hello World Java ";
str = str.replaceAll("\\s", "");
System.out.println(str);
}
}
output:
HelloWorldJava
2). Find and replace white Space
Here we are passing the string to the removeAll function, we traverse the string characters one by one if the character is not equal to the white space then it will print the character otherwise it will skip the character.
package com.javacodestuffs.core.strings;
public class CustomWhiteSpaceRemove {
static int i;
static void removeAll(String s) {
StringBuffer sb = new StringBuffer();
for (i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch != ' ') {
sb.append(ch);
}
}
System.out.print(sb);
}
public static void main(String args[]) {
String str = "Hello World Welcome to Java Programming ";
System.out.println(str);
CustomWhiteSpaceRemove.removeAll(str);
}
}
output:
Hello World Welcome to Java Programming
HelloWorldWelcometoJavaProgramming
Post/Questions related to Remove all whitespaces from String in Java
How to check if the string is whitespace java?
Commonly used String Operations in Java
Convert Character Array to String in Java
Array to String in Java
In this article, we have seen how to Remove all whitespaces from String in Java with examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment