2

Such as I have a NSString is str = @"我就是测试一下" or str = @"我" . And I want to restrict a certain byte length. such as byteLength = 10.

I know the subSrtring is not the str.length=10 How to get a certain bytes length subString from a NSString, thank you

4

3 回答 3

4

您可以使用dataUsingEncoding方法NSDataNSString. 然后使用lengthandbytes属性得到byte lengthorbytes

那么如果NSData's length > your certain length你应该使用+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length;方法来获取一定长度的字节NSData,你应该小心返回NSData可能无法解码NSString

最后你可以使用- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;方法得到NSString你想要的结果

您可以使用以下代码:

- (NSString *)fetchStringWithOriginalString:(NSString *)originalString withByteLength:(NSUInteger)length
{
    NSData* originalData=[originalString dataUsingEncoding:NSUTF8StringEncoding];
    const char *originalBytes = originalData.bytes;

    //make sure to use a loop to get a not nil string.
    //because your certain length data may be not decode by NSString
    for (NSUInteger i = length; i > 0; i--) {

        @autoreleasepool {
            NSData *data = [NSData dataWithBytes:originalBytes length:i];
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            if (string) {
                return string;
            }
        }

    }
    return @"";
}

您可以像这样调用上述方法:

NSString* originalString= @"我就是测试一下";
NSString *string = [self fetchStringWithOriginalString:originalString withByteLength:10];
NSData* stringData=[string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"10 bytes string : %@ ; it only %i bytes",string,stringData.length);

结果 : 在此处输入图像描述

小心:- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;可能会退货nil

正如苹果所说:- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;回报:

通过使用编码将数据中的字节转换为 Unicode 字符来初始化的 NSString 对象。返回的对象可能与原始接收者不同。如果由于某种原因初始化失败(例如,如果数据不代表用于编码的有效数据),则返回 nil。

因此,您应该使用 for 循环来获取可以解码的最近长度数据NSSting

于 2013-09-03T03:39:39.780 回答
0

利用

[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]
于 2013-09-03T03:36:30.420 回答
0

我认为这应该有效:

NSUInteger bytes = [incomingText lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

if (bytes > MAX_TEXT_BYTES) {
    int length = [incomingText length];
    int cutoffIndex = (int)(MAX_TEXT_BYTES * (length / bytes));
    return [incomingText substringToIndex:cutoffIndex];
}
于 2016-05-02T19:11:14.720 回答