Tag Archives: NSString

How to remove the first n characters from an NSString

There’s a convenient method for that by the name of substringFromIndex. This example removes the first character:

substringFromString takes only one parameter which specifies where to start the new string. The first character is 0 based, like in arrays. The parameter can’t be longer than the original string’s length for obvious reasons.

How to extract first n characters of an NSString

We can use substringWithRange for this, which requires us to define a range:

You create a range by specifying where the substring should start (the first character is 0, like in an array), then specify how many characters from there you want to use.

To grab just the first character you’d specify a range like this:

How to remove the last n characters from an NSString

We can use the substringToIndex method for this, using the length of our original string minus 1:

How to convert an NSString into an integer

Imagine you had an NSString and wanted to save it as an integer value.
You can use the intValue method for that:

To do the reverse, you can use the initWithFormat method:

How to read the contents of a text file into an NSString

Imagine we had a file called myfile.txt which is a standard text file. On each line we have a new item we’d like to read so that our app can do something with it. Here’s how we do that:

It is likely that instead of a long list of text we’d rather have each line in a separate string.
Thankfully there’s a method for this:

How to combine NSString objects

Say you had two NSString objects, firstString and secondString and you’d like to combine them into a new string called comboString. You can use the convenience method stringWithFormat for this:

Any variable is passed at the end of the string, replacing each %@ symbol.

How to convert an integer into a string (text object)

I keep forgetting how to do this so here it is: if you have an integer and you want to print it out, say in a UILabel you can use the initWithFormat method of NSString like so:

The secret here is the @”%d” which is called a String Format Specifier (search for it in the Developer Docs).

How to concatenate strings (i.e. print several at a time)

This is really simple in PHP, however it’s not obvious in Objective-C because you’re not printing the strings directly. Rather you print two objects that point to each string. There is a method though which has the same effect: stringByAppendingString. Here’s how you use it:

It gets a bit more complex when you want to add three or more together; each stringByAppendingString expression needs to be in [brackets] before you add another one, like so: