|
How to remove duplicate white spaces in a String
The following example shows removing duplicate white spaces in a given string.
|
package com.bethecoder.articles.basics.dup_white;
public class DuplicateWhiteSpaceTest {
/**
* @param args
*/
public static void main(String[] args) {
String str = "Be The Coder Java Examples";
long start = System.nanoTime();
String result = removeDuplicateWhiteSpace(str);
long timeTaken = System.nanoTime() - start;
System.out.println(result);
System.out.println("Time taken : " + timeTaken + " ns");
start = System.nanoTime();
result = removeDuplicateWhiteSpace2(str);
timeTaken = System.nanoTime() - start;
System.out.println(result);
System.out.println("Time taken : " + timeTaken + " ns");
}
public static String removeDuplicateWhiteSpace(String str) {
return str.replaceAll("\\s+", " ");
}
public static String removeDuplicateWhiteSpace2(String str) {
StringBuilder sb = new StringBuilder();
boolean space = false;
for (int i = 0; i < str.length() ; i ++) {
if (!space && str.charAt(i) == ' ') {
sb.append(' ');
space = true;
} else if (str.charAt(i) != ' ') {
sb.append(str.charAt(i));
space = false;
}
}
return sb.toString();
}
}
|
| |
It gives the following output,
Be The Coder Java Examples
Time taken : 495314 ns
Be The Coder Java Examples
Time taken : 17600 ns
|
|