mrgonuts
mrgonuts

Reputation: 56

Replace all characters in a string

Hi I've searched but can't find the answer I'm looking for or I'm not reading it right.

I have a NSString I use

NSString *string1 = [infolist objectAtIndex:0];
NSUInteger len = [string1 length];

Is it possible to replace all characters not white spaces with say a * or some other unreadable character.

Example: this is a string to **** ** * ******

Upvotes: 2

Views: 660

Answers (1)

Stream
Stream

Reputation: 9493

Make use of regular expressions if you target OS X 10.7 and later:

NSString *originalString = @"This is a string";
NSString *nonspaceRegexp = @"\\S"; // = /\S/
NSStringCompareOptions options = NSRegularExpressionSearch;
NSRange replaceRange = NSMakeRange(0, originalString.length);
NSString *replacedString = [originalString
                            stringByReplacingOccurrencesOfString:nonspaceRegexp
                                                      withString:@"*"
                                                         options:options
                                                           range:replaceRange];
NSLog(@"%@", replacedString); // **** ** * ******

Upvotes: 9

Related Questions