How can I truncate an NSString to a set length?

Posted by nevan on Stack Overflow See other posts from Stack Overflow or by nevan
Published on 2010-06-01T18:33:42Z Indexed on 2010/06/01 20:33 UTC
Read the original article Hit count: 1430

Filed under:
|
|
|

I searched, but surprisingly couldn't find an answer.

I have a long NSString that I want to shorten. I want the maximum length to be around 20 characters. I read somewhere that the best solution is to use substringWithRange. Is this the best way to truncate a string?

NSRange stringRange = {0,20};
NSString *myString = @"This is a string, it's a very long string, it's a very long string indeed";
NSString *shortString = [myString substringWithRange:stringRange];

It seems a little delicate (crashes if the string is shorter than the maximum length). I'm also not sure if it's Unicode-safe. Is there a better way to do it? Does anyone have a nice category for this?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c