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

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -