-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveWhiteSpace.java
38 lines (29 loc) · 997 Bytes
/
RemoveWhiteSpace.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package string;
import java.util.Scanner;
public class RemoveWhiteSpace {
/**
* Main method of the class for the following question:
* Remove spaces from a string in Java.
* */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String: ");
var input = scanner.nextLine();
System.out.println(removeWhiteSpaceBruteForce(input));
System.out.println(removeWhiteSpace(input));
}
// Brute Force:
private static String removeWhiteSpaceBruteForce(String input) {
StringBuilder stringBuilder = new StringBuilder();
for (char ch : input.toCharArray()) {
if (!Character.isWhitespace(ch)) {
stringBuilder.append(ch);
}
}
return stringBuilder.toString();
}
// Optimized Method:
private static String removeWhiteSpace(String input) {
return input.replaceAll(" ", "");
}
}