×
Namespaces

Variants
Actions
(Difference between revisions)

Normalize string whitespaces with J2ME

From Nokia Developer Wiki
Jump to: navigation, search
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Add ArticleMetadata)
hamishwillee (Talk | contribs)
m (Hamishwillee - Add General Programming)
Line 1: Line 1:
 +
[[Category:Java ME]][[Category:Code Snippet]]
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
Line 21: Line 22:
 
|author= [[User:Jappit]]
 
|author= [[User:Jappit]]
 
}}
 
}}
[[Category:Java ME]][[Category:Code Snippet]]
+
 
 
A simple method to normalize String multiple whitespaces (replacing them with a single whitespace). For example, to normalize the String:<br/>
 
A simple method to normalize String multiple whitespaces (replacing them with a single whitespace). For example, to normalize the String:<br/>
 
''"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Normalize&nbsp;&nbsp;&nbsp;&nbsp;all&nbsp;&nbsp;whitespaces&nbsp;&nbsp;"''
 
''"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Normalize&nbsp;&nbsp;&nbsp;&nbsp;all&nbsp;&nbsp;whitespaces&nbsp;&nbsp;"''

Revision as of 04:28, 19 July 2012

Article Metadata
Article
Created: jappit (06 May 2008)
Last edited: hamishwillee (19 Jul 2012)

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();
}
104 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×