iOS for C# Developer - part 2: strings
String operations in Objective-C are very verbose in comparison to C#.
Let's assume the following string definition for all below examples:
I think this is the most common operation. In C# it is very simple:
* For concatenation in C#, consider using
StringBuilder class (if performance matters).
NSMutableString type has to be used. Thus, if we have
NSString created, we have to do the following:
A bit of work, huh?
To get substring from letter 3 to 7 in C#:
To split sentences in our sample string in C#, we would do:
Also, pretty similar.
This operation is much more verbose than its equivalent in C#. To replace spaces with underscores, in C# we do:
Looks pretty the same, but long, custom names preceding actual parameters make code unnecessary long (IMO).
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.
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.