×
Namespaces

Variants
Actions
Revision as of 09:13, 15 August 2013 by hamishwillee (Talk | contribs)

Normalize string whitespaces with J2ME

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: jappit (06 May 2008)
Last edited: hamishwillee (15 Aug 2013)

A simple method to normalize String multiple whitespaces (replacing them with a single whitespace). For example, to normalize the String:
"     Normalize    all  whitespaces  "
to:
" Normalize all whitespaces ".

String normalizeWhitespaces(String s)
{
StringBuffer res = new StringBuffer();
 
int prevIndex = 0;
 
int currIndex = -1;
 
int stringLength = s.length();
 
String searchString = " ";
 
while((currIndex = s.indexOf(searchString, currIndex + 1)) >= 0)
{
res.append(s.substring(prevIndex, currIndex + 1));
 
while(currIndex < stringLength && s.charAt(currIndex) == ' ')
{
currIndex++;
}
 
prevIndex = currIndex;
}
res.append(s.substring(prevIndex));
 
return res.toString();
}
80 page views in the last 30 days.
×