Question

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

Était-ce utile?

La solution

you can use dataUsingEncoding method to get a NSData from NSString. And then use length and bytes property to get the byte length or bytes

Then if the NSData's length > your certain length you should use + (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length; method to get the certain length byte NSData you should be careful that the return NSData may be can not decode by NSString

At last you can use - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; method to get the result NSString you want

And you can use the code below:

- (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 @"";
}

you can call the above method like this :

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);

The Result : enter image description here

Be careful: the - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; may be return nil

As apple said:the - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; Return:

An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

So you should use a for loop to get a nearest length data which can decode by NSSting

Autres conseils

Use

[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]

I think this should work:

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];
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top