Working with Strings in Objective-C: NSString and NSMutableString
Creating NSString Instances
There are several ways to create a NSString object in Objective-C.
1. Direct Assignment
NSString *text = @"Hello World";
2. Object Initialization
NSString *textObject = [[NSString alloc] init];
textObject = @"Initial Text";
3. Formatted Creation
NSString *formattedText = [NSString stringWithFormat:@"%@", @"Formatted String"];
4. Reading from a File
NSError *fileError = nil;
NSString *fileContent = [NSString stringWithContentsOfFile:@"/path/too/file.txt"
encoding:NSUTF8StringEncoding
error:&fileError];
if (fileError) {
NSLog(@"Error reading file: %@", fileError);
}
5. Writing to a File
NSString *outputText = @"Data to write";
NSError *writeError = nil;
BOOL success = [outputText writeToFile:@"/path/to/output.txt"
atomically:YES
encoding:NSUTF8StringEncoding
error:&writeError];
if (success) {
NSLog(@"File written successfully");
} else {
NSLog(@"Write failed: %@", writeError);
}
Using NSURL for String Operations
Writing Strings with NSURL
NSURL *fileURL = [NSURL URLWithString:@"file:///Users/username/Documents/data.txt"];
NSString *content = @"Sample content";
BOOL writeResult = [content writeToURL:fileURL
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
if (writeResult) {
NSLog(@"Content saved to URL");
}
Reading Strings with NSURL
NSURL *sourceURL = [NSURL URLWithString:@"file:///Users/username/Documents/data.txt"];
NSString *loadedContent = [NSString stringWithContentsOfURL:sourceURL
encoding:NSUTF8StringEncoding
error:nil];
NSLog(@"Loaded: %@", loadedContent);
String Comparison and Manipulation
Comparing Strings
NSString *first = @"Apple";
NSString *second = @"Banana";
NSComparisonResult result = [first compare:second];
switch (result) {
case NSOrderedAscending:
NSLog(@"%@ comes before %@", first, second);
break;
case NSOrderedSame:
NSLog(@"Strings are equal");
break;
case NSOrderedDescending:
NSLog(@"%@ comes after %@", first, second);
break;
}
Case-Insensitive Comparison
NSString *upper = @"HELLO";
NSString *lower = @"hello";
NSComparisonResult caseResult = [upper compare:lower options:NSCaseInsensitiveSearch];
Equality Check
NSString *strA = @"Test";
NSString *strB = @"Test";
if ([strA isEqualToString:strB]) {
NSLog(@"String are identical");
}
Prefix and Suffix Checking
NSString *url = @"https://example.com";
if ([url hasPrefix:@"https://"]) {
NSLog(@"Secure URL");
}
NSString *filename = @"document.pdf";
if ([filename hasSuffix:@".pdf"]) {
NSLog(@"PDF file");
}
Finding Substrings
NSString *mainString = @"The quick brown fox jumps over the lazy dog";
NSRange foundRange = [mainString rangeOfString:@"brown"];
if (foundRange.location != NSNotFound) {
NSLog(@"Found at location: %lu, length: %lu",
(unsigned long)foundRange.location,
(unsigned long)foundRange.length);
}
Reverse Search
NSRange reverseRange = [mainString rangeOfString:@"the" options:NSBackwardsSearch];
String Extraction
NSString *original = @"Objective-C Programming";
// From index to end
NSString *fromIndex = [original substringFromIndex:10]; // "Programming"
// Start to index
NSString *toIndex = [original substringToIndex:9]; // "Objective"
// Using NSRange
NSRange extractRange = NSMakeRange(11, 11);
NSString *withRange = [original substringWithRange:extractRange]; // "Programming"
String Replacement
NSString *sentence = @"I like apples";
NSString *modified = [sentence stringByReplacingOccurrencesOfString:@"apples"
withString:@"oranges"];
// Result: "I like oranges"
String Length
NSString *sample = @"Length Test";
NSUInteger strLength = [sample length]; // 10
Character Access
unichar character = [sample characterAtIndex:4]; // 'g'
Type Conversion
NSString *numberText = @"123.45";
double doubleValue = [numberText doubleValue];
float floatValue = [numberText floatValue];
int intValue = [numberText intValue];
C String Interoperability
NSString *objcString = @"Foundation";
const char *cString = [objcString UTF8String];
char cArray[] = "C String";
NSString *converted = [NSString stringWithUTF8String:cArray];
Whitespace Handling
NSString *spaced = @" Trim Me ";
// Remove all spaces
NSString *noSpaces = [spaced stringByReplacingOccurrencesOfString:@" " withString:@""];
// Trim leading/trailing whitespace
NSString *trimmed = [spaced stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Trim specific characters
NSString *withLetters = @"abcTextcba";
NSString *letterTrimmed = [withLetters stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"abc"]];
Working with NSRange
NSRange is a fundamental structure in Foundation for representing ranges.
// Structure definitoin
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
Creating NSRange Instances
// Direct initializtaion
NSRange directRange = {3, 7};
// Separate assignment
NSRange separateRange;
separateRange.location = 5;
separateRange.length = 12;
// Using NSMakeRange
NSRange madeRange = NSMakeRange(10, 20);
NSMutableString Overview
NSMutableString extends NSString, providing mutable string operations similar to Java's StringBuilder.
Creating Mutable Strings
NSMutableString *mutable = [NSMutableString string];
Appending Content
[mutable appendString:@"Initial "];
[mutable appendFormat:@"formatted number: %d", 42];
Character Manipulation
// Delete characters
NSRange deleteRange = NSMakeRange(5, 3);
[mutable deleteCharactersInRange:deleteRange];
// Insert string
[mutable insertString:@"INSERTED " atIndex:0];
// Replace characters
NSRange replaceRange = NSMakeRange(0, 8);
[mutable replaceCharactersInRange:replaceRange withString:@"REPLACEMENT"];
Important Considerations
- Initialization Method Matters
// This creates NSString, not NSMutableString
NSMutableString *incorrect = @"Immutable";
// Correct mutable creation
NSMutableString *correct = [NSMutableString stringWithString:@"Mutable"];
- String Property Overwrites Content
NSMutableString *dynamic = [NSMutableString string];
[dynamic appendString:@"Building "];
[dynamic appendString:@"content"];
// Overwrites entire string
dynamic.string = @"Reset";
- Bitmask Enumerations String comparison options use bitmask enumerations where values are powers of two.
// Multiple options can be combined
NSUInteger options = NSCaseInsensitiveSearch | NSLiteralSearch;
NSComparisonResult combined = [str1 compare:str2 options:options];