以字节为单位获取UTF-8字符串长度的最佳方法?

时间:2021-05-21 22:22:22

I want to get a cString from NSString.
So we used c​String​Using​Encoding:​ method.
However, the return value of the c​String​Using​Encoding:​ method is not guaranteed.
(Apple's doc: The returned C string is guaranteed to be valid only until either the receiver is freed.)

So Apple recommends the get​CString:​max​Length:​encoding: method.
I want to pass the exact length to maxLength.

我想从NSString获得一个cString。所以我们使用了c String Using Encoding:方法。但是,不保证c String Using Encoding:方法的返回值。 (Apple的doc:返回的C字符串保证只有在释放接收器之前才有效。)因此,Apple推荐使用get CString:max Length:encoding:方法。我想将确切的长度传递给maxLength。

Example 1)

NSString *tmp = @"中日韓" // cString 9bytes
char *buffer = new tmp[9 + 1];
[tmp getCString:buffer maxLength:9+1 encoding:NSUTF8String​Encoding];

Example 2)

NSString *tmp = @"中日韓123" // cString 12bytes
char *buffer = new tmp[12 + 1];
[tmp getCString:buffer maxLength:12+1 encoding:NSUTF8String​Encoding];

Is there a way to know the lengths of 9 and 12 in the example above?

有没有办法知道上面例子中9和12的长度?

2 个解决方案

#1


4  

// Add one because this doesn't include the NULL
NSUInteger maxLength = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;

#2


3  

You can use cStringUsingEncoding to get the length. If you need the resulting char * to live longer than tmp, then simply copy the C-string:

您可以使用cStringUsingEncoding来获取长度。如果您需要生成的char *比tmp更长寿,那么只需复制C字符串:

NSString *tmp = @"中日韓" // cString 9bytes
const char *cStr = [tmp cStringUsingEncoding:NSUTF8StringEncoding];
size_t len = strlen(cStr);
char *buffer = new tmp[len + 1];
strcpy(buffer, cStr);

#1


4  

// Add one because this doesn't include the NULL
NSUInteger maxLength = [string maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;

#2


3  

You can use cStringUsingEncoding to get the length. If you need the resulting char * to live longer than tmp, then simply copy the C-string:

您可以使用cStringUsingEncoding来获取长度。如果您需要生成的char *比tmp更长寿,那么只需复制C字符串:

NSString *tmp = @"中日韓" // cString 9bytes
const char *cStr = [tmp cStringUsingEncoding:NSUTF8StringEncoding];
size_t len = strlen(cStr);
char *buffer = new tmp[len + 1];
strcpy(buffer, cStr);