Question

I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as "This is a message with $specially formatted$ content".

However, I need to change the '$' at the start of the special formatting with a '[' and the '$' at the end with ']'. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!

Is there a simple way to recognise a substring encapsulated by '$' and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple '$' substrings.

Thanks!

Was it helpful?

Solution

You can use regular expressions:

NSMutableString *str = [@"Hello $World$, foo $bar$." mutableCopy];

NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\$([^$]*)\\$"
                                                  options:0
                                                    error:NULL];
[regex replaceMatchesInString:str
                      options:0
                        range:NSMakeRange(0, [str length])
                 withTemplate:@"[$1]"];
NSLog(@"%@", str);
// Output:
// Hello [World], foo [bar].

The pattern @"\\$([^$]*)\\$" searches for

$<zero_or_more_characters_which_are_not_a_dollarsign>$

and all occurrences are then replaced by [...]. The pattern contains so many backslashes because the $ must be escaped in the regular expression pattern.

There is also stringByReplacingMatchesInString if you want to create a new string instead of modifying the original string.

OTHER TIPS

I think replaceOccurrencesOfString: won't work cause you have start$ and end$.

But if you seperate the Strings with [string componentsSeperatedByString:@"$"] you get an Array of substrings, so every second string is your "$specially formatted$"-string

This should work!

NSString *str = @"This is a message with $specially formatted$ content";
NSString *original = @"$";
NSString *replacement1 = @"[";
NSString *replacement2 = @"]";

BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
    str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
    start = !start;
    rOriginal = [str rangeOfString: original];
}

NSLog(@"%@", str);

Enjoy Programming!

// string = @"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:@"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
   [out appendString:components[i]];
   [out appendString: (i % 2) ? @"]" : @"[" ];
}
// out = @"This is a [special markup] sentence."

Try this one

NSMutableString *string=[[NSMutableString alloc]initWithString:@"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];


NSMutableString *string=[[NSMutableString alloc]initWithString:@"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];

BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
    if ([string characterAtIndex:i]=='$') {
        if (open) {
            [string replaceCharactersInRange:NSMakeRange(i, 1) withString:@"["];
            open=!open;
        }
        else{
            [string replaceCharactersInRange:NSMakeRange(i, 1) withString:@"]"];
            open=!open;
        }
    }
}
NSLog(@"-->%@",string);

Output:

-->This is a message with [specially formatted] content. This is a message with [specially formatted] content
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top