Alex Rivera | Logout

How can I truncate an NSString to a set length?

Asked 2010-06-01T18:33:42.507
75

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?

Edit
Report

1 Answer

0

All NSString operations are Unicode-safe, as NSString is essentially a unichar array internally. Even if the string is in a different encoding it's converted to your specified encoding when it's displayed.

answered 2010-06-01T18:52:59.357

Your Answer