user2131907
user2131907

Reputation: 352

How to add a specific character to a set of characters in a NSString

I want to add a specific character in front of a set of characters in a NSString.

For example:

NSString *input = @"abc^ 123 # //> <";    
NSString *insertBefore = @"~";
NSCharacterSet *needBeInserted = [NSCharacterSet 
                        characterSetWithCharactersInString:@"~#^/<>"];

Expected result: any characters in needBeInserted that appears in input will add insertBefore.

result = @"abc~^ 123 ~# ~/~/~> ~<";

Is there an elegant way to do it? Instead of use multiple lines of stringByReplacingOccurrencesOfString?

Upvotes: 1

Views: 602

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You may put your chars into a character class and use a regex based replacement:

[~#^/<>]

Replace with ~$0 where $0 inserts the whole match text into the resulting string. See the regex demo.

See the Objective-C demo online:

NSError *error = nil;
NSString *input = @"abc^ 123 # //> <";
NSString *pat = @"[~#^/<>]";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pat options:nil error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:input 
        options:0 
        range:NSMakeRange(0, [input length]) 
        withTemplate:@"~$0"];
NSLog(@"%@", modifiedString);

Result: abc~^ 123 ~# ~/~/~> ~<

Upvotes: 1

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

You have to search the characters and replace it:

NSRange searchRange = NSMakeRange( 0,[input length] );
NSRange charRange;
while( (charRange = [input rangeOfCharactersFromSet:escapeSet options:NSBackwardSearch).length range:searchRange)
{
  // It is allowed to have a 0-length range: Insertion
  input = [input stringByReplacingCharactersInRange:NSMakeRange(charRange.location, 0) withString:@"\"];

  // Shorten the search range
  searchRange = NSMakeRange(0, charRange.location);
}

Written in Safari. You should test if for edge cases and typos.

Another way is to make an array of (single-letter) strings out of the character set and replace occurrences of it with a combination with the escape character. Seems to be more complex and less natural to me.

Upvotes: 0

Related Questions