iOS开发NSString篇:字符串每隔几个字符插入某个字符

时间:2022-04-26 21:30:49

e.g

卡号:1234567890123456789
需求:将该卡号每四个字符用空格分隔
结果:1234 5678 9012 3456 789

算法思路:

遍历字符串,每隔4个字符插入一个空格

iOS代码实现:

//每隔4个字符添加一个空格的字符串算法
- (NSString *)dealWithString:(NSString *)number
{
NSString *doneTitle = @"";
int count = 0;
for (int i = 0; i < number.length; i++) {

count++;
doneTitle = [doneTitle stringByAppendingString:[number substringWithRange:NSMakeRange(i, 1)]];
if (count == 4) {
doneTitle = [NSString stringWithFormat:@"%@ ", doneTitle];
count = 0;
}
}
NSLog(@"%@", doneTitle);
return doneTitle;
}