-
Notifications
You must be signed in to change notification settings - Fork 0
/
prog15.5.m
70 lines (56 loc) · 1.86 KB
/
prog15.5.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Basic String Operations - Mutable Strings
#import <Foundation/Foundation.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *str1 = @"This is a string A";
NSString *search, *replace;
NSMutableString *mstr;
NSRange substr;
// Create mutable string from nonmutable
mstr = [NSMutableString stringWithString: str1];
NSLog(@"%@", mstr);
// Insert characters
[mstr insertString: @" mutable" atIndex: 7];
NSLog(@"%@", mstr);
// Effective concatentation if insert at end
[mstr insertString: @" and string B" atIndex: [mstr length]];
NSLog(@"%@", mstr);
// Or can user appendString directly
[mstr appendString: @" and string c"];
NSLog(@"%@", mstr);
// Delete substring based on range
[mstr deleteCharactersInRange: NSMakeRange(16,13)];
NSLog(@"%@", mstr);
// Find range first and then use it for deletion
substr = [mstr rangeOfString: @"string B and "];
if (substr.location != NSNotFound) {
[mstr deleteCharactersInRange: substr];
NSLog(@"%@", mstr);
}
// Set the mutable string directly
[mstr setString: @"This is string A"];
NSLog(@"%@", mstr);
// Now let's replace a range of chars with another
[mstr replaceCharactersInRange: NSMakeRange(8, 8) withString: @"a mutable string"];
NSLog(@"%@", mstr);
// Search and replace
search = @"This is";
replace = @"An example of";
substr = [mstr rangeOfString: search];
if (substr.location != NSNotFound) {
[mstr replaceCharactersInRange: substr withString: replace];
NSLog(@"%@", mstr);
}
// Search and replace all occurreces
search = @"a";
replace = @"X";
substr = [mstr rangeOfString: search];
while (substr.location != NSNotFound) {
[mstr replaceCharactersInRange: substr withString: replace];
substr = [mstr rangeOfString: search];
}
NSLog(@"%@", mstr);
[pool drain];
return 0;
}