For ex: "__I_love___India___";
in this string i want to remove leading and trailing spaces completely and multiple spaces with in the string in java.
i.e. output should be
"I love India
";
For ex: "__I_love___India___";
in this string i want to remove leading and trailing spaces completely and multiple spaces with in the string in java.
i.e. output should be
"I love India
";
Another way is to use StringTokenizer with a space as a token separator. Read each token and write it back to StringBuilder.
import java.util.*;
class Words
{
/**
* Convenience method.
*/
public static StringBuilder deduplicateSpaces(String text)
{
return deduplicateDelimiters(text, " ");
}
public static StringBuilder deduplicateDelimiters(String text, String delim)
{
StringTokenizer st = new StringTokenizer(text, delim);
StringBuilder sb = new StringBuilder();
boolean firstRun = true;
while (st.hasMoreTokens())
{
sb.append(firstRun? "" : delim) //prevent delimiter on the first token
.append(st.nextToken() ); //append token itself
if (firstRun) { firstRun = false; }
}
return sb;
}
public static void main (String[] args)
{
String textS = " A bbbb ccccc ";
String textU = "____A_____bbbb____ccccc___";
System.out.println(deduplicateSpaces(textS));
System.out.println(deduplicateDelimiters(textU, "_"));
}
}
Output is:
A bbbb ccccc
A_bbbb_ccccc
Method trim ()
removes leading and trailing spaces. In order to remove duplicate spaces from the middle of the string you can use regular expression.
s2 = s1.replaceAll ("\\s+", " ").trim ();
Try this logic:
String input = "I love India ";
input = input.trim().replaceAll("\\s+", " ");
The idea here is use two separate operations for handling whitespace at the beginning/end and whitespace between words. We want to completely remove whitespace at the beginning/end and String#trim()
does that nicely. Then, between words only a single space should appear, and a regex replacement handles this case.
You can try one of these:
String after = before.trim().replaceAll("\\s+", " ");
String after = before.replaceAll("\\s{2,}", " ").trim();
String after = StringUtils.normalizeSpace(String str);
Try replaceAll("\\s{2,}", " ").trim();
where str is a String variable containing the text you want to strip white space from and use trim for leading and trailing white space
Updated as a result of comments as I forgot to replace multiple white space with a single space