how to get first three characters of an NSString?

Objective CCocoa

Objective C Problem Overview


How can I return the first three characters of an NSString?

Objective C Solutions


Solution 1 - Objective C

 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

Solution 2 - Objective C

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.

Solution 3 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristian GossainView Question on Stackoverflow
Solution 1 - Objective CGameLoadingView Answer on Stackoverflow
Solution 2 - Objective CdreamlaxView Answer on Stackoverflow
Solution 3 - Objective CpeakView Answer on Stackoverflow