What is the length in bytes of a NSString?

我的未来我决定 提交于 2019-12-03 16:22:18

问题


How do I get the bytes length of NSString? if myString contains "hallo", myString.length will return 5, but how many actual bytes are taken?


回答1:


NSString *test=@"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSUInteger bytes = [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%i bytes", bytes);



回答2:


To get the bytes use

NSData *bytes = [string dataUsingEncoding:NSUTF8StringEncoding];

Then you can check bytes.length

Number of bytes depend on the string encoding




回答3:


Well:

NSString* string= @"myString";
NSData* data=[string dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger myLength = data.length;



回答4:


From the Apple documentation:

An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of 16-bit platform-endian values, with index values starting at 0.

So the memory used by an NSString is 2 bytes per character plus whatever fixed memory is used by the object itself.



来源:https://stackoverflow.com/questions/11245188/what-is-the-length-in-bytes-of-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!