forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveWhiteSpaces.java
37 lines (28 loc) · 899 Bytes
/
RemoveWhiteSpaces.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
package strings;
public class RemoveWhiteSpaces {
/*
* Given a null terminated string, remove any white spaces (tabs or spaces).
* Eg: Input - "All greek to me."
* Output - "Allgreektome"
*
* Runtime Complexity - Linear, O(n).
* Memory Complexity - Constant, O(1).
*
* */
public static String removeWhiteSpaces(String s) {
char[] arr = s.toCharArray();
int readIndex = 0;
String result = "";
while (readIndex < arr.length && arr[readIndex] != '\0') {
if(arr[readIndex] != ' ' && arr[readIndex] != '\t') {
result += arr[readIndex];
}
++readIndex;
}
return result;
}
public static void main(String[] args) {
String string = " All greek to me. \n";
System.out.println(removeWhiteSpaces(string));
}
}