美文网首页
字符串每隔几个字符 插入新的字符

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

作者: 1234yws | 来源:发表于2016-03-09 09:31 被阅读69次

    //方法一

    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;

    }

    相关文章

      网友评论

          本文标题:字符串每隔几个字符 插入新的字符

          本文链接:https://www.haomeiwen.com/subject/jqakkttx.html