Remove whitespace from an array of string.
While creating an array of string from a sentence, I’m encountering multiple spaces and need to remove them in order to create a new reverse sentence from the given sentence. How do I remove extra spaces in the middle of two words?
Example: a good example
How do I remove two spaces in between good and example ?
Here is the code I’m using:
public class reverseString {
public static void main(String[] args) {
String s = "a good example";
String ans = revString(s);
System.out.println(ans);
}
static String revString(String s) {
String[] arr = s.split(" ");
List<String> list = new ArrayList<String>();
StringBuilder ans = new StringBuilder();
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == null) {
continue;
} else {
ans.append(arr[i].trim());
// ans.append(" ");
}
}
String is = ans.toString();
return is.trim();
}
}
The expected output was: example good a
The output I’m getting is: example good a
Comparing the string at the I-th index with " " should result in continuation of the loop. Instead it jumps to the else condition.
>Solution :
The parameter to method split (of class java.lang.String) is a regular expression. Just add a + (i.e. "plus" symbol – which means one or more) to the value of the parameter.
import java.util.ArrayList;
import java.util.List;
public class ReverseString {
public static void main(String[] args) {
String s = "a good example";
String ans = revString(s);
System.out.println(ans);
}
static String revString(String s) {
String[] arr = s.split(" +"); // CHANGE HERE - added '+'
List<String> list = new ArrayList<String>();
StringBuilder ans = new StringBuilder();
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == null) {
continue;
}
else {
ans.append(arr[i].trim());
ans.append(" ");
}
}
String is = ans.toString();
return is.trim();
}
}
Running the above code produces the following output:
example good a