iOS for C# Developer - part 2: strings
This post is part of the series: iOS for C# Developer. First part can be found here.
String operations in Objective-C are very verbose in comparison to C#.
Let's assume the following string definition for all below examples:
NSString *str = @"Some string. Another string.";
Concatenation
I think this is the most common operation. In C# it is very simple:
string result += " Appended string.";
* For concatenation in C#, consider using StringBuilder
class (if performance matters).
In Objective-C, NSMutableString
type has to be used. Thus, if we have NSString
created, we have to do the following:
NSMutableString *temp = [[NSMutableString alloc] initWithString:str];
[temp stringByAppendingString:@" Appended string."];
str = temp;
A bit of work, huh?
Substring
To get substring from letter 3 to 7 in C#:
string result = str.Substring(3,5);
In Objective-C:
NSString *result = [str substringWithRange:NSMakeRange(3,5)];
Pretty straightforward.
Split
To split sentences in our sample string in C#, we would do:
string[] result = str.Split(". ");
In Objective-C:
NSArray *result = [str componentsSeparatedByString:@". "];
Also, pretty similar.
Replace
This operation is much more verbose than its equivalent in C#. To replace spaces with underscores, in C# we do:
string result = str.Replace(" ", "_");
In Objective-C:
NSString *result = [str stringByReplacingOccurrencesOfString:@" " withString:@"_"];
Looks pretty the same, but long, custom names preceding actual parameters make code unnecessary long (IMO).
Real-world example
Usually we need a few string operations working together. Let's apply above operations together. For example: we want to get only the second sentence from our string with underscores instead of spaces.
In C#:
string result = str.Split(new [] {". "}, StringSplitOptions.RemoveEmptyEntries)[1].Replace(' ','_');
In Objective-C:
NSString *result = [[str componentsSeparatedByString:@". "][1] stringByReplacingOccurrencesOfString:@" " withString:@"_"];
Summary
Some of above operations are easier in Swift (e.g., concatenation looks the same like in C#), but some are still very verbose (e.g., substring, replace). However, the syntax is more similar to C#. The message passing syntax is something you need to get use to in Objective-C, not only in case of string operations.