0

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 "-".

rmaddy
  • 314,917
  • 42
  • 532
  • 579
zhuber
  • 5,364
  • 3
  • 30
  • 63

1 Answers1

3

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];
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579