objective c - Replace special character or whitespace with - -
i want make every string this:
"this-is-string-one"
so main string contain:
"this! string, one"
so basicaly replace !?., whitespace , characters "-".
something best handled regular expression:
nsstring *somestring = @"this! string, one"; nsstring *newstring = [somestring stringbyreplacingoccurrencesofstring:@"[!?., ]+" withstring:@"-" options: nsregularexpressionsearch range:nsmakerange(0, somestring.length)]; nslog(@"\"%@\" converted \"%@\"", somestring, newstring);
the output be:
"this! string, one" converted "this-is-string-one"
the regular expression [!?., ]+
means sequence of 1 or more of characters listed between square brackets.
update:
if want truncate trailing hyphen can this:
if ([newstring hassuffix:@"-"]) { newstring = [newstring substringtoindex:newstring.length - 1]; }
Comments
Post a Comment