Measure the length of an nsstring in Chinese and English.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.