字符串每隔几个字符 插入新的字符

2016-03-09  本文已影响69人  1234yws

//方法一

NSMutableString *mst = [[NSMutableString alloc] init];;

NSString *str = @"hqrtyuiolmnbv";

[mst setString:str];

for (int i = 0; i < str.length*2; i++) {

if (i%2 == 0) { // 根据奇偶判断是否插入

[mst insertString:@" " atIndex:i]; //插入空格

}

}

//方法二

- (NSString *)addSpaceFromSring:(NSString *)str {

int count = 0;

long long int a = str.longLongValue;

while (a != 0) {

count++;

a /= 10;

}

NSMutableString *muString = [NSMutableString stringWithString:str];

NSMutableString *newString = [NSMutableString string];

while (count > 1) {

count -= 1;

NSRange rang = NSMakeRange(muString.length - 2, 2);

NSString *cunStr = [muString substringWithRange:rang];

[newString insertString:cunStr atIndex:0];

[newString insertString:@" " atIndex:0];

[muString deleteCharactersInRange:rang];

}

[newString insertString:muString atIndex:0];

return newString;

}

上一篇下一篇

猜你喜欢

热点阅读