In this tutorial, we can use the Java String built-in replace() or replaceAll() methods to replace spaces with dashes (-) easily.
Table of contents:
- 1. Using replace()
- 2. Using replaceAll()
- 3. Which method should we use?
- 4. Real-world Example:
- 5. References
1. Using replace()
The replace() method replaces all occurrences of a specific character.
ReplaceSpaceExample.java
package com.mkyong;
public class ReplaceSpaceExample {
public static void main(String[] args) {
String original = "Hello World from Java";
String replaced = original.replace(" ", "-");
System.out.println("Original: " + original);
System.out.println("Replaced: " + replaced);
}
}
Output:
Terminal
Original: Hello World from Java
Replaced: Hello-World-from-Java
2. Using replaceAll()
We can also use replaceAll() if we need to use regular expressions.
ReplaceSpaceExampleRegex.java
package com.mkyong;
public class ReplaceSpaceExampleRegex {
public static void main(String[] args) {
String original = "Java Programming Made Easy";
String replaced = original.replaceAll("\\s+", "-");
System.out.println("Original: " + original);
System.out.println("Replaced: " + replaced);
}
}
Output:
Terminal
Original: Java Programming Made Easy
Replaced: Java-Programming-Made-Easy
Explanation of \\s+
\smatches any whitespace character (spaces, tabs, line breaks).+means one or more occurrences of the preceding element (\s).
Together, \s+ effectively matches any sequence of whitespace characters, replacing them all with a single dash.
3. Which method should we use?
- Use
replace()for simple character replacement (recommended for basic scenarios). - Use
replaceAll()with regex if we want to replace different types of whitespace, such as tabs or multiple consecutive spaces.
4. Real-world Example:
Imagine we are creating SEO-friendly URLs by converting blog titles into URL slugs.
URLSlugExample.java
package com.mkyong;
public class URLSlugExample {
public static void main(String[] args) {
String blogTitle = "Top 10 Java Programming Tips";
String urlSlug = blogTitle.toLowerCase().replaceAll("\\s+", "-");
System.out.println("SEO URL Slug: " + urlSlug);
}
}
Output:
Terminal
SEO URL Slug: top-10-java-programming-tips