HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Java remove extra white spaces between words in String

Java remove extra white spaces between words in String

Learn how to remove extra white spaces between words from a String in Java. Given 3 examples remove extra spaces using regular expression, StringBuiffer and lastly Apache Commons StringUtils class.

1. Remove extra white spaces with StringUtils

This approach, using StringUtils.normalizeSpace() is most readable and it should be preferred way to remove unwanted white spaces between words.

This function returns the argument string with whitespace normalized by –

  1. using trim(String) to remove leading and trailing whitespace, and then
  2. replacing sequences of whitespace characters by a single space

1.1. Maven dependency

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

1.2. Java program to remove spaces between words

// uneven spaces between words
String blogName = "how to   do    in  java   .         com"; 

String nameWithProperSpacing = StringUtils.normalizeSpace( blogName );

System.out.println( nameWithProperSpacing );

Program output.

how to do in java . com

2. Remove extra white spaces between words with regular expression

Using regular expression, to replace 2 or more white spaces with single space, is also a good solution.

We are using regex pattern as “\\s+”.

  1. \s matches a space, tab, new line, carriage return, form feed or vertical tab.
  2. + says one or more occurrences.
// uneven spaces between words
String blogName = "how to   do    in  java   .         com"; 

String nameWithProperSpacing = blogName.replaceAll("\\s+", " ");

System.out.println( nameWithProperSpacing );

Program output.

how to do in java . com

Note that this method will not trim the String. That means there might be single space at start at end of string, if original string has such white spaces at beginning or end.

3. Replace multiple spaces with single space using StringBuiffer

StringBuiffer can also help you to get string from uneven spaced strings. This is complete programmatic approach and may not be suitable for large strings.

// uneven spaces between words
String blogName = "how to   do    in  java   .         com"; 

StringTokenizer st = new StringTokenizer(blogName, " ");
StringBuffer sb = new StringBuffer();

while(st.hasMoreElements())
{
    sb.append(st.nextElement()).append(" ");
}

String nameWithProperSpacing = sb.toString();

System.out.println( nameWithProperSpacing );

//trim leading and trailing white spaces
nameWithProperSpacing = nameWithProperSpacing.trim();
		
System.out.println( nameWithProperSpacing );

Program output.

how to do in java . com

Please note that, as in case of regular expression, this method also may leave leading and trailing white spaces. So do not forget to trim the string after you have remove extra whitespaces between words in parameter string.

Happy Learning !!

Read More:

  1. Remove only leading spaces of a String
  2. Remove only trailing spaces of a String

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)