Reputation: 3453
I using card.io for scanning my credit/debit card. When the scan is completed I receive string like '3456789023456789'
. I am setting this string value to my textfield. Now I want that when setting the string value to textfield it should appear in this format '3456-7890-2345-6789'
.
Upvotes: 0
Views: 1428
Reputation: 9842
You can use following code to insert hiphen(-) after every forth character:
NSMutableString *requiredString = [[NSMutableString alloc] init];
for(int i = 0; i < string.length; i = i+4) {
NSString *subString = [string substringWithRange:NSMakeRange(i, 4)];
if(i+4 < string.length) {
[requiredString appendString:[NSString stringWithFormat:@"%@-", subString]];
}
else {
[requiredString appendString:[NSString stringWithFormat:@"%@", subString]];
break;
}
}
Upvotes: 1
Reputation: 3359
for( NSInteger i = 3 ; i < aMutableString.length ; i += 4 ) {
[aMutableString insertString:@"-" atIndex: i + i/4 ] ;
}
Upvotes: 0
Reputation: 2503
NSMutableString *str = [[NSMutableString alloc] initWithString:@"3456789023456789"];
int four = 4;
for(int i = 0; i < 3 ; i++){
[str insertString:@"-" atIndex:(i==0 ? four : four*(i+1)+i )];
}
Upvotes: 1
Reputation: 2360
You should have a NSMutableString
and use the function
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
example [myMutableString insertString:@"-" atIndex:multiplesOfFour]
Upvotes: 2