Calculate the length of an nsstring. Use the length method returns the number of Unicode characters in the specified er. Both English and Chinese characters are of the same length, for example, the length of @ "ABCDE my" is 7, which is actually not consistent with the number of words entered on Weibo. in Weibo, the length is 5 (actually 4.5, the length of "ABCDE my F" is also 5), So if you limit the length of characters in uitextview, You need to recalculate the following:
-------------------- Reprint: http://mobilesolutions.blog.163.com/blog/static/18922417620116133910181/ statistics including Chinese and English mix nsstring String Length
Converts the length obtained from an nsstring type string to an ascii-like length, for example, two Chinese characters, two English characters, and one English character.
Because the length obtained by calling the [nsstring length] method is one Chinese Character and one English character is one byte
[Nsstring lengthofbytesusingencoding: nsasciistringencoding] The method cannot recognize Chinese encoding, which is really worrying.
So I want to get a char * type string and traverse it and organize it into a format similar to ASCII encoding.
[Nsstring cstringusingencoding: nsunicodestringencoding] The function obtains a constchar * pointer and then traverses the string. If it encounters/0, it skips it. Otherwise, the length is greater than 1. Here is the code to share it with you:
1 - (int)convertToInt:(NSString*)strtemp { 2 3 int strlength = 0; 4 char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; 5 for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) { 6 if (*p) { 7 p++; 8 strlength++; 9 }10 else {11 p++;12 }13 }14 return (strength+1)/2;15 16 }
Measure the length of an nsstring in Chinese and English.