How can I truncate an NSString to a set length? How can I truncate an NSString to a set length? objective-c objective-c

How can I truncate an NSString to a set length?


Actually the part about being "Unicode safe" was dead on, as many characters combine in unicode which the suggested answers don't consider.

For example, if you want to type é. One way of doing it is by typing "e"(0x65)+combining accent" ́"(0x301). Now, if you type "café" like this and truncate 4 chars, you'll get "cafe". This might cause problems in some places.

If you don't care about this, other answers work fine. Otherwise, do this:

// define the range you're interested inNSRange stringRange = {0, MIN([myString length], 20)};// adjust the range to include dependent charsstringRange = [myString rangeOfComposedCharacterSequencesForRange:stringRange];// Now you can create the short stringNSString *shortString = [myString substringWithRange:stringRange];

Note that in this way your range might be longer than your initial range length. In the café example above, your range will expand to a length of 5, even though you still have 4 "glyphs". If you absolutely need to have a length less than what you indicated, you need to check for this.


Since this answer isn't actually in this list, the simplest and most sensible one-liner:

NSString *myString = @"This is a string, it's a very long string, it's a very long string indeed";myString = (myString.length > 20) ? [myString substringToIndex:20] : myString;


Swift 4

let trimToCharacter = 20let shortString = String(myString.prefix(trimToCharacter))

Happy Coding.