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:
Concatenation
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).
In Objective-C, NSMutableString
type has to be used. Thus, if we have NSString
created, we have to do the following:
A bit of work, huh?
Substring
To get substring from letter 3 to 7 in C#:
In Objective-C:
Pretty straightforward.
Split
To split sentences in our sample string in C#, we would do:
In Objective-C:
Also, pretty similar.
Replace
This operation is much more verbose than its equivalent in C#. To replace spaces with underscores, in C# we do:
In Objective-C:
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#:
In Objective-C:
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.