The method of calculating string length in Java and the understanding of u4E00 and u9FBB

  • 2020-04-01 01:32:39
  • OfStack

When strings are encoded in unicode, the string length calculation method finds out the range of Chinese characters represented in unicode encoding from "\u4E00" to "\u9FBB". Since a Chinese character represents two characters, the following method can be used to calculate the length of strings
 
public static int getCharLength(String content) { 
int count = 0; 
for (int i = 0, len = content.length(); i < len; ++i) { 
if ('u4E00' <= content.charAt(i) && 'u9FBB' >= content.charAt(i)) { 
count++; 
} 
} 
return content.length()+count; 
} 

Other coding methods can be calculated according to this principle

Related articles: