Albert Renshaw
Albert Renshaw

Reputation: 17882

Quickest method - commas between string components

I have an NSString, let's say "Hello"... What is the quickest way to fill this string up with commas in between each character? (Including before the first character)
So the returned string would be, ",H,E,L,L,O"


I was just gong to make a for loop and have a variable that goes up 2 each time a comma is added that way it will go past the new comma and the next letter and add a comma then check if that variable divided by 2 is greater than the length of the original string... Is there a better method?

Upvotes: 0

Views: 172

Answers (2)

Monolo
Monolo

Reputation: 18253

If you fancy regular expressions, you can use those. Not sure about performance, so for long strings you might want to verify that.

The meat of it is two lines of code:

NSString *orgString = @"Hello"; // Not part of the meat, for the line counters out there...

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"." 
                                                                       options:0
                                                                         error:nil];

NSString *commaString = [regex stringByReplacingMatchesInString:orgString
                                                        options:0
                                                          range:NSMakeRange(0, orgString.length)
                                                   withTemplate: @",$0"];

I have taken the liberty to not check the regular expression for errors, as it consists of just a single dot. That really ought to compile also in future versions of the OS.

Upvotes: 0

user529758
user529758

Reputation:

Or you can just append characters to a mutable string:

NSString *original = @"Hello";
NSUInteger len = original.length;

NSMutableString *newStr = [NSMutableString stringWithCapacity:len * 2];
for (int i = 0; i < len; i++) {
    [newStr appendFormat:@",%C", [original characterAtIndex:i]];
}

Upvotes: 3

Related Questions