Get the first two characters of NSString

I have a string, I'm trying to get the first 2 characters and the rest of the string. Here is how I am trying to do this:

NSString *textAll = [arrayOfMessages objectAtIndex:indexPath.row]; NSString *textMessage = [textAll substringFromIndex:2]; NSString *textType = [textAll substringToIndex:1]; 

textAll has the following form: HE message itself .....

textType should return 'HE' textMessage should return "the message itself ....." Textmessage now gives me a message, but I can not get textType ...

+7
ios
source share
1 answer

To get the first two characters of a string, you want:

 NSString *textType = [textAll substringToIndex:2]; // <-- 2, not 1 

From the documentation:

substringToIndex:

Returns a new string containing the characters of the receiver before , but not including , the one that has the specified index.

(Note that the method expects the string length to be at least 2 characters, otherwise it throws an exception.)

+22
source share

All Articles