Home > CodeSnippets, Development, iOS, Objective-C > NSString Basics

NSString Basics

Creating strings

NSString *myFirstString = @"foo";
NSString *mySecondString = [[NSString alloc] initWithFormat:
   @"%@%@%@i", myFirstString, @"bar", 1];

Comparing strings

NSString *myString = @"foo";
if([myString isEqualToString:@"foo"]) {
   NSLog (@"Strings are equal!");
}

Finding strings within strings

NSString *myString = @"foo";
NSString *searchForMe = @"Howdi";
NSRange range = [myString rangeOfString : searchForMe];
int location = range.location;
int length = range.length;

if (location != NSNotFound) {

   NSString *locationAndLength = [[NSString alloc] initWithFormat:
      @"Location: %i, length: %i", location, length];
   NSLog(@"I found something.");
   NSLog(locationAndLength);
}

Replacing strings within strings

NSString *myString = @"foo";
myString = [myString stringByReplacingOccurancesOfString:@"oo"
   withString:@"uu"];

Extracting substrings from strings

There are 3 methods that allow to extract substrings from a parent string:

  • -substringToIndex:
  • -substringWithRange:
  • -substringFromIndex: (which respectively take a substring from the beginning, middle, and end of a parent string)

The first method substringToIndex returns a new string which is composed of the characters from the beginning of the receiver string up to (but not including) the character at the specified index:

NSString *aString = @"Running out of ideas for strings.";
NSString *substring = [aString substringToIndex:7];
// result: @"Running"

The method substringFromIndex works in the same way, except now the substring starts at the specified index of the receiver (including the character at the index) and includes all the characters to the end of the receiver:

NSString *substring = [aString substringFromIndex:25];
// result: @"strings"

Finally, we have the method which lets us arbitrarily extract a substring from anywhere within the parent string substringWithRange. The argument to this method is an NSRange:

NSString *substring = [aString substringWithRange:NSMakeRange(15, 5)];
// result: @"ideas"

Here the range starts with the 15th character, “i”, and extends to include the next four characters, giving us a length of 5, “ideas”.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: