Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in NSString

I am trying to replace all characters except last 4 in a String with *'s.
In objective-c there is a method in NSString class replaceStringWithCharactersInRange: withString: where I would give it range (0,[string length]-4) ) with string @"*". This is what it does: 123456789ABCD is modified to *ABCD while I am looking to make ********ABCD. I understand that it replaced range I specified with string object. How to accomplish this ?

like image 297
ARC Avatar asked Oct 04 '11 15:10

ARC


People also ask

How to replace string in objective C?

To replace a character in objective C we will have to use the inbuilt function of Objective C string library, which replaces occurrence of a string with some other string that we want to replace it with.


2 Answers

I'm not sure why the accepted answer was accepted, since it only works if everything but last 4 is a digit. Here's a simple way:

NSMutableString * str1 = [[NSMutableString alloc]initWithString:@"1234567890ABCD"];
NSRange r = NSMakeRange(0, [str1 length] - 4);
[str1 replaceCharactersInRange:r withString:[[NSString string] stringByPaddingToLength:r.length withString:@"*" startingAtIndex:0]];
NSLog(@"%@",str1);
like image 133
James Boutcher Avatar answered Sep 28 '22 10:09

James Boutcher


NSError *error;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d" options:NSRegularExpressionCaseInsensitive error:&error];

NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"*"];
like image 42
Lefteris Avatar answered Sep 28 '22 12:09

Lefteris