Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first two characters of NSString

Tags:

ios

I have a string an I am trying to get the first 2 characters and the rest of the string. This is how I am trying to do it:

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

the textAll has this form: HEthe message itself.....

textType should return 'HE' textMessage should return 'the message itself.....' Textmessage now gives me the message but I can't seem to be able to get the textType...

like image 558
Alessandro Avatar asked Nov 02 '13 21:11

Alessandro


People also ask

How do I find the first character of a string in Objective C?

You want: NSString *firstLetter = [codeString substringToIndex:1];

What is NSString in objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What is NSString in swift?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.


1 Answers

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 up to, but not including, the one at a given index.

(Note that the method expects that the string is at least 2 characters long, otherwise it throws an exception.)

like image 100
Martin R Avatar answered Oct 12 '22 07:10

Martin R