The Objective-C class for strings is NSString. Strings are typically created by direct assignment or by calling one of the NSString class methods.

Please note; this tutorial covers strings in objective-c only, whilst it may link to apple documentation about other methods and functions this guide will not stray onto other topics, please read Beginners Guide to Objective-C for Developers to further develop your knowledge.

Just like other languages, strings are enclosed and defined by the use of “double quotes”, however in Objective-C an NSString also comes with the prefix of the @ sign, Like so:


1
NSString *yourString = @"This is a string, you like?";

Creating and Formatting the String

Take a look at the apple documentation on NSString Class Reference to check the number of ways that you can create and return strings. The most common and the one you’re likely to be using is stringWithFormat:


1
2
3
NSString *yourString = @"iOS-Blog";
NSString *yourNewString = [NSString stringWithFormat:@"Check out:    %@ for awesome tutorials.];
// yourNewString is now @"Check out: iOS-Blog for awesome tutorials."

Common string format specifiers are: %@ another object. (this calls the :description verb on the specified object, which must then return an NSString.), %d an integer number, %f, %.4f floating point number (with .n digits after the decimal place).

You can also get the length of a string which can be obtained using the length method:


1
2
NSString *yourString = @"iOS-Blog";
int yourLength = [yourString length];       // yourLength is equals to 8

Joining an Array of Strings

For this, you need to use NSArray’s componentsJoinedByString:


1
2
3
4
NSArray *yourWords = [NSArray arrayWithObjects:@"iOS-Blog", @"is", @"just", @"awesome", nil];
NSString *sentence = [yourWords componentsJoinedByString:@" "];

// *sentence is now: @"iOS-Blog is just awesome"

Equals to

There may become a time you need to determine if two of your strings are equal, for this we use: isEqualToString and we implement it like so:


1
2
3
4
5
6
NSString *yourString = @"iOS-Blog";

if ([yourString isEqualToString:@"iOS-Blog"]) {
    /// Out put the result to the NSLog
    NSLog(@"Yes, They are both equal");
}

Replacing Characters in a String

Many languages offer you the chance to replace information within a string, for example PHP used the str_replace method. However, in Objective-C we use the stringByReplacingOccurrencesOfString method.

So lets say that you wanted to take out all the references to the word red:


1
NSString *newString = [textField.text stringByReplacingOccurrencesOfString:@"red" withString:@""];

Splitting Strings into an Array

We use a method called componentsSeparatedByString to achieve this:


1
2
3
4
NSString *yourString = @"This is a test string";
NSArray *yourWords = [myString componentsSeparatedByString:@" "];

// yourWords is now: [@"This", @"is", @"a", @"test", @"string"]

if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:


1
2
3
4
5
6
NSString *yourString = @"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
                      [NSCharacterSet characterSetWithCharactersInString:@"-/"]
                    ];

// yourWords is now: [@"Foo", @"bar", @"iOS", @"Blog"]

Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:


1
2
3
4
5
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

Trim Spaces from the End of a String

Sometimes you might need to remove white spacing, sometimes you just want to, for this we will use the whitespaceCharacterSet method to remove the white spaces from both ends of the string:


1
NSString *yourString = [whitespaceString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

If you want to also remove newlines from the string however, use the whitespaceAndNewlineCharacterSet:


1
NSString *yourString = [whitespaceString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

Concatenating and Appending Strings

This is quite possibly the most useful thing that you will need to know. Concatenating strings. So you have two strings and you need them to go together. Like firstName and LastName. Then this is how you would do that:


1
2
3
4
5
6
NSString *firstName = @"iOS-";
NSString *lastName = @"Blog";
// Concatenate them into a new string
NSString *fullName = [string1 stringByAppendingString:string2];
// fullName is now @"iOS-Blog"  
// firstName and lastName are unchanged and can be used again.

This is a little different if you are using NSMutableString method, you just simply call the appendString method


1
2
3
4
NSMutableString *string1 = [NSMutableString stringWithString:@"This is"];
NSString *string2 = @" a test.";
[string1 appendString:string2];
NSLog(@"string1: %@", string1);         // string1 is now @"This is a test."

If you would like to concatenate 3 strings then it’s probably easier to construct a new string out of the three by using stringWithFormat: method


1
2
NSString *allThreeStrings = [NSString stringWithFormat:@"%@ %@ and boring %@",
                             firstString, secondString, thirdString];

Finding and Replacing Substrings

For this we will use the NSString method: rangeOfString to find out whether a substring exists within another string:


1
2
NSString *theString = @"iOS-Blog.com";
NSRange isCom = [theString rangeOfString:@".com"];

NSRange is a struct with two parts:

	.location
	.length

If the substring is not found, rangeOfString returns {NSNotFound, 0}.

There is a shorter and easier way to test whether a s string is found:


1
2
3
if ( [theString rangeOfString:@".com"].location != NSNotFound ) {
    // do something here if the string is found
}

Replacing or removing a Substring:


1
2
3
4
5
6
7
8
NSString *theString = @"ios-blog.com";
NSRange tldr = [domainName rangeOfString:@".com"];

if (tldr.location != NSNotFound) {
    NSLog(@"range of .com: %d, %d", tldr.location, tldr.length);
    domainName = [domainName stringByReplacingCharactersInRange:tldr withString:@""];
    NSLog(@"removed .com, domain is now: %@", domainName);
}

Converting NSString to NSData

Please check out Quick Tip: Converting NSString to NSData

That’s it, I hope that you find this tutorial informative. Please leave any questions below.

Problems?

We have a new Questions and Answers section so you can get help from the awesome community.

Ask a Question

Enjoyed this post?

Subscribe to our RSS Feed or Follow us on twitter to keep up to date with the latest from iOS-Blog. Remember, Sharing is caring so please click one of the following options:

Tags: , , , ,