Table of Contents Previous Section

Commonly Used String Methods

The following sections list the most commonly used NSString and NSMutableString methods. The methods covered are grouped in the following categories:

Creating Strings

The methods in this section are class methods, as denoted by the plus sign (+). You use class methods to send messages to a class-in this case, NSString and NSMutableString. For more information on class methods, see "Messaging in WebScript" in the "Using WebScript" chapter.

+ string
Returns an empty string. Usually used to create NSMutableStrings. NSStrings created with this method are permanently empty.
/* Most common use */
id mutableString = [NSMutableString string];

/* May not be what you want */
id string = [NSString string];

+ stringWithFormat:
Returns a string created by substituting arguments into a specified format string in the manner that printf() does in the C programming language. In WebScript, only the "at sign" (@) conversion character is supported, and it expects a corresponding id argument.
// These are fine
id party = [NSString stringWithFormat:@"Party date: %@", partyDate];
id mailto = [NSString stringWithFormat:@"mailto: %@", [person email]];
id footer = [NSString stringWithFormat:
@"Interaction %@ in session %@.",
	numberOfInteractions, sessionNumber];

// C users, NO! This won't work. Only %@ is supported.
id string = [NSString stringWithFormat:@"%d of %d %s", x, y, 
	cString];

+ stringWithString:
Returns a string containing the same contents as a specified string. This method is usually used to create an NSMutableString from an NSString. For example, the following statement:
id mutableString = [NSMutableString stringWithString:@"Change me."];

creates an NSMutableString from a constant NSString object.

+ stringWithContentsOfFile:
Returns a string created by reading characters from a specified file. For example, the following statement creates an NSString containing the contents of the file specified in path.
id fileContents = [NSString stringWithContentsOfFile:path];

See also writeToFile:atomically:.

Combining and Dividing Strings

- stringByAppendingFormat:
Returns a string made by appending to the receiver a string constructed from a specified format string and following arguments in the manner of stringWithFormat:. For example, assume the variable guestName contains the string "Rena". Then the following code excerpt:
id string = @"Hi";
id message = [string stringByAppendingFormat:@", %@!", guestName];

produces the string message with contents "Hi, Rena!".

- stringByAppendingString:
Returns a string object made by appending a specified string to the receiver. This code excerpt, for example:
id errorTag = @"Error: ";
id errorString = @"premature end of file.";
id errorMessage = [errorTag stringByAppendingString:errorString];

produces the string "Error: premature end of file.".

- componentsSeparatedByString:
Returns an NSArray containing substrings from the receiver that have been divided by a specified separator string. For example, the following statements:
id toolString = @"wrenches, hammers, saws";
id toolArray = [toolString componentsSeparatedByString:@", "];

produce an NSArray containing the strings "wrenches", "hammers", and "saws."

See also componentsJoinedByString: (NSArray and NSMutableArray).

- substringToIndex:
Returns a string object containing the characters of the receiver up to, but not including, the one at the specified index.

- substringFromIndex:
Returns a string object containing the characters of the receiver from the one at the specified index to the end.

Comparing Strings

- compare:
Returns -1 if the receiver precedes a specified string in lexical ordering, 0 if it is equal, and 1 if it follows. For example, the following statements:
if ([@"hello" compare:@"Hello"] == -1) {
	result = [NSString stringWithFormat:
			@"'%@' precedes '%@' lexicographically.",
			@"hello", @"Hello"];
}

result in an NSString result with the contents "`hello' precedes `Hello' lexicographically."

- caseInsensitiveCompare:
Same as compare:, but case distinctions among characters are ignored.

- isEqual:
Returns YES if a specified object is equivalent to the receiver, NO otherwise. An object is equivalent to a string if the object is an NSString or an NSMutableString and compare: returns 0. For example, the following statements:
if ([string isEqual:newString) {
	result = @"Found a match";
}

assign the contents "Found a match" to result if string and newString are lexicographically equal.

Converting String Contents

- doubleValue
Returns the the floating-point value of the receiver's text as a double, skipping white space at the beginning of the string

- floatValue
Returns the floating-point value of the receiver's text as a float, skipping white space at the beginning of the string.

- intValue
Returns the integer value of the string's text, assuming a decimal representation and skipping white space at the beginning of the string.

Modifying Strings

Warning: The following methods are not supported by NSString. They are only available to NSMutableString objects.

- appendFormat:
Appends a constructed string to the receiver. Creates the new string by using stringWithFormat: method with the arguments listed. For example, in the following code excerpt, assume the variable guestName contains the string "Rena":
id message = [NSMutableString stringWithString:@"Hi"];
[message appendFormat:@", %@!", guestName];

message has the resulting contents "Hi, Rena!".

- appendString:
Adds the characters of a specified string to the end of the receiver. For example, the following statements create an NSMutableString and append another string to its initial value:
id mutableString = [NSMutableString stringWithFormat:@"Hello "];
[mutableString appendString:@"world!"];

mutableString has the resulting contents "Hello world!".

- setString:
Replaces the characters of the receiver with those in a specified string. For example, the following statement replaces the contents of an NSMutableString with the empty string:
[mutableString setString:@""];

Storing Strings

- writeToFile:atomically:
Writes the string to a specified file, returning YES on success and NO on failure. If YES is specified for atomically:, this method writes the string to an auxiliary file and then renames the auxiliary file to the specified path. In this way, it ensures that the contents of the specified path do not become corrupted if the system crashes during writing. The resulting file is suitable for use with stringWithContentsOfFile:. For example, the following code excerpt:
id errorLog = [NSString stringWithContentsOfFile:errorPath];
id newErrorLog = [errorLog stringByAppendingFormat:@"%@: %@.\n",
		timeStamp, @"premature end of file."];
[newErrorLog writeToFile:errorPath atomically:YES];

reads the contents of an error log stored in a file, appends a new error to the log, and saves the updated log to the same file.

Table of Contents Next Section