NSString Archives

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: NSString *complete = @”12345″; NSString *cutOff = [complete substringFromIndex:1]; NSLog(@”%@”, cutOff); // cutOff is now 2345 substringFromString takes only one parameter which specifies where to start the new string. The first character is 0 based, like in arrays. […]

How to extract first n characters of an NSString

We can use substringWithRange for this, which requires us to define a range: NSString *something = @”123456789″; NSRange myRange = NSMakeRange(2, 3); something = [something substringWithRange:myRange]; // something is now 345 You create a range by specifying where the substring should start (the first character is 0, like in an array), then specify how many […]

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: NSString *myString = @”47″; int myInt = [myString intValue]; To do the reverse, you can use the initWithFormat method: int myInt = 32; NSString *myOtherString = [[NSString alloc]initWithFormat:@”%i”, myInt];

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: // get a reference to our file NSString *myPath = [[NSBundle mainBundle]pathForResource:@”myfile” ofType:@”txt”]; // read the […]

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: NSString *comboString = [[NSString alloc]initWithFormat:@”First %@ and second %@”, firstString, secondString]; 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: NSString *myNumber; myNumber = [[NSString alloc] initWithFormat:@”%d”, myInteger]; self.myLabel.text = myNumber; The secret here is the @”%d” which […]

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: self.myLabel.text = [@”This is ” stringByAppendingString: @”my label”]; It gets […]