如何获得 NSString 的前三个字符?

如何返回 NSString 的前三个字符?

89101 次浏览
 mystr=[mystr substringToIndex:3];

Be sure your string has atleast 3 ch.. o.e. it will crash the app.

Here are some other links to check NSsting operations...

Link1

Link2

Apple Link

First, you have to make sure that the string contains at least 3 characters:

NSString *fullString = /* obtain from somewhere */;
NSString *prefix = nil;


if ([fullString length] >= 3)
prefix = [fullString substringToIndex:3];
else
prefix = fullString;

substringToIndex: will throw an exception if the index you provide is beyond the end of the string.

the right way is:

text = [text substringToIndex:NSMaxRange([text rangeOfComposedCharacterSequenceAtIndex:2])];

substringToIndex of NSString is indexing by code unit, emoji takes two code units.

make sure check the index yourself.