Calculation of string length in Objective-c

Source: Internet
Author: User

We know that in C, using sizeof () to calculate the number of bytes occupied in the memory, after referencing string.h, use strlen () to calculate the length of the string (not including).

In Object-c, the "Length" method can return the length of a string.

For example:nsstring * str [email protected] "12345"; int a = 0; a = [str lenght]; At this point the value of a is the length of the string str, which is 5.

It is worth mentioning that the length method in OC in the calculation of string lengths and C there are several differences, in C, if the string has a Chinese character is calculated by three bytes of length, such as char * str = "haha"; the length of this string is 6, but in OC, The length of each symbol is 1 regardless of whether the string is in Chinese or other characters, for example: NSString * str = @ "haha"; then the length of STR is 2.

Let's take a few examples to better understand:

1) string length calculation in pure English:

NSString *str = @ "Wanghy";

Nsuinteger len = [str length];

The value of Len at this time is 6.

NSLog (@ "len =%ld", Len);

2) length calculation of strings in pure Chinese

Each Chinese character is treated as a single character

NSString *STR2 = @ "The world is so big, I want to see";

len = [str2 length];

The value of Len should be 11.

NSLog (@ "len =%ld", Len);

3) mixed in Chinese and English

Summary: Whether Chinese or English, in OC is considered to be a character

NSString *STR3 = @ "haha itcast";

len = [STR3 length];

NSLog (@ "len =%ld", Len); Len = 10;

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Calculation of string length in Objective-c

Related Article

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.