简体   繁体   中英

iPhone : insert a character inside a dynamic string

I have a dynamic string suppose

  NSString *originalString = @"Hello my Phone : 123123123 abc 987";

In the above string first i have to check were numbers are present inside the string which i got it by doing below code :-

 NSString *newString = [[MessageStr componentsSeparatedByCharactersInSet:
                        [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                       componentsJoinedByString:@""];

result i got in newString is 123123123987

But my problem is not getting out numbers from string, i just want to add a special character after every number inside the string which is dynamic.

like i want to make my string like this :-

NSString *originalString = @"Hello my Phone : 1,2,3,1,2,3,1,2,3 abc 9,8,7";

So, please any one can suggest me, what's best possible way to achieve above string.

Thanks in advance.

I finally succeed by doing the following code :-

NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"([0-9])" options:0 error:NULL];
NSString *newString = [regexp stringByReplacingMatchesInString:MessageStr options:0 range:NSMakeRange(0, MessageStr.length) withTemplate:@"$0,"];
NSLog(@"Changed %@", newString);

Thanks @nsgulliver by posting answer in the link :-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM