There are many ways to replace blank characters in a String in Java. Regex is one of the most popular methods to replace blank characters in Java Strings. In today’s article, we will see different approaches.
How to replace blank characters in a String
There are many classes like StringBuilder, StringBuffer etc., but the replaceAll method in the String class itself is much simpler and does the job in just one line. Let us see how to replace blank characters in String using replace() method:
String removeSpaces = "I m a g i n a r y ";
System.out.println(removeSpaces);
for(int i=0;i<removeSpaces.length();i++)
removeSpaces = removeSpaces.replace(" ", "");
System.out.println(removeSpaces);
Replacing blank spaces from StringBuffer is a bit lengthy but we will still show it before we move on to replaceAll():
/*If we have a Stringbuffer instead of String */
System.out.println("........ using stringbuffer.......");
StringBuffer sbuff = new StringBuffer();
sbuff.append(" I m a g ");
sbuff.append(" i n a r y ");
// We use the trim method to remove leading and trailing spaces
/* The advantage of StringBuffer is that you don't have to use equals operator every time you modify the string */
/*to remove the spaces in between, we have to convert the string to array and split the string,
* then join it again */
String[] arrimg = sbuff.toString().trim().split(" ");
StringBuffer sbuffnew = new StringBuffer();
for(int i=0;i<arrimg.length;i++)
sbuffnew.append(arrimg[i]);
System.out.println(sbuffnew);
Now, let’s use String replaceAll() method:
String withoutspace = removeSpaces.replaceAll(" ", "");
/*No need to put a loop or any conversion*/
System.out.println(withoutspace);
A better way of using regex is to use the delimiter and the pattern:
String withoutspace = removeSpaces.replaceAll("\\s", "");
Conclusion
We have seen the various ways of removing spaces in a String, not only leading and trailing but also the ones that appear in between.
People are also reading:
Leave a Comment on this Post