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. […]
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 […]
We can use the substringToIndex method for this, using the length of our original string minus 1: NSString *something = @”12345″; something = [something substringToIndex:(something.length – 1)]; // something is now 1234
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];
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 […]
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.
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 […]
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 […]