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:
Method | Purpose |
---|---|
NSString | Used to create an immutable string. |
NSMutableString | Used to create a mutable string that can be changed. |
length | Returns the length of the string. |
stringWithFormat | Formats a string with specified values. |
substringWithRange | Extracts a substring from the string based on a specified range. |
isEqualToString | Compares two strings for equality. |
stringByAppendingFormat | Appends 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
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
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.