Contents

String in Objective-C

Strings in Objective-C

Strings are a fundamental concept in programming, used to represent sequences of text. In Objective-C, strings are objects that store sequences of characters. These characters can include letters, digits, symbols, or any other textual data. Objective-C provides various classes and methods for creating and manipulating strings, allowing for different ways of working with text.

Types of Strings

1. NSString: This is an immutable object that represents a sequence of characters. Once created, the string cannot be modified.
2. NSMutableString: This is a mutable object that allows changes after creation. You can add, remove, or modify characters.
3. CFString: This is a Core Foundation object used to represent sequences of Unicode characters.

Built-in Methods for Strings

Objective-C offers several classes and methods for creating and manipulating strings. Here are some commonly used ones:

MethodPurpose
NSStringUsed to create an immutable string.
NSMutableStringUsed to create a mutable string that can be changed.
lengthReturns the length of the string.
stringWithFormatFormats a string with specified values.
substringWithRangeExtracts a substring from the string based on a specified range.
isEqualToStringCompares two strings for equality.
stringByAppendingFormatAppends a formatted string to the existing string.
Example 1: Creating a String with NSString

In this example, we create a string using the NSString class.

				
					#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    // Define a string
    NSString *greeting = @"Hello, Objective-C!";
    
    // Print the string
    NSLog(@"%@", greeting);
    
    return 0;
}

				
			

Output:

				
					Hello, Objective-C!

				
			

Example 2: Formatting a String with Values

Here, we format a string by inserting a variable value into the string using stringWithFormat.

				
					#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    // Create an integer variable
    int appleCount = 12;
    
    // Format a string with a value
    NSString *formattedString = [NSString stringWithFormat:@"I have %d apples.", appleCount];
    
    // Print the formatted string
    NSLog(@"%@", formattedString);
    
    return 0;
}

				
			

Output:

				
					I have 12 apples.