-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveArbitrarySpaces.java
More file actions
50 lines (41 loc) · 1.14 KB
/
Copy pathRemoveArbitrarySpaces.java
File metadata and controls
50 lines (41 loc) · 1.14 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static String removeArbitraryWhiteSpaces(String str){
String temp = str;
StringTokenizer tokens = new StringTokenizer(temp, " ");
StringBuilder sbr = new StringBuilder();
while(tokens.hasMoreTokens()){
sbr.append(tokens.nextToken());
sbr.append(" ");
}
return sbr.toString().trim();
}
public static String removeArbitraryWhiteSpacesBasic(String str){
int spaceCount = 0;
boolean wordStarted = false;
StringBuilder sbr = new StringBuilder();
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ' '){
spaceCount++;
}else{
if(spaceCount >= 1 && wordStarted){
sbr.append(" ");
}
sbr.append(str.charAt(i));
wordStarted = true;
spaceCount = 0;
}
}
return sbr.toString();
}
public static void main (String[] args) throws java.lang.Exception
{
String str = " The sky is blue ";
System.out.println(removeArbitraryWhiteSpacesBasic(str));
}
}