zhuber
zhuber

Reputation: 5524

Replace special character or whitespace with -

I want to make every string look like this:

"this-is-string-one"

So main string could contain:

"This! is string, one"

So basicaly replace !?., whitespace and characters like that with "-".

Upvotes: 0

Views: 2001

Answers (1)

rmaddy
rmaddy

Reputation: 318814

Something like this is best handled by a regular expression:

NSString *someString = @"This! is string, one";
NSString *newString = [someString stringByReplacingOccurrencesOfString:@"[!?., ]+" withString:@"-" options: NSRegularExpressionSearch range:NSMakeRange(0, someString.length)];
NSLog(@"\"%@\" was converted to \"%@\"", someString, newString);

The output will be:

"This! is string, one" was converted to "This-is-string-one"

The regular expression [!?., ]+ means any sequence of one or more of the characters listed between the square brackets.

Update:

If you want to truncate any trailing hyphen then you can do this:

if ([newString hasSuffix:@"-"]) {
    newString = [newString substringToIndex:newString.length - 1];
}

Upvotes: 3

Related Questions