美文网首页想法简友广场
iOS 字符串每4位用空格隔开

iOS 字符串每4位用空格隔开

作者: 海边的遐想 | 来源:发表于2022-08-16 16:57 被阅读0次
    image.png

    NSString *text = self.model.orderNo;
    ///首先定义一个0123456789\b的字符集
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    ///去掉字符中的空格
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    while (text.length > 0) {
    ///每4位截取下
    NSString *subString = [text substringToIndex:MIN(text.length, 4)];
    newString = [newString stringByAppendingString:subString];
    if (subString.length == 4) {
    //当字符长度为4的时候拼接上空格
    newString = [newString stringByAppendingString:@" "];
    }
    text = [text substringFromIndex:MIN(text.length, 4)];
    }
    ///去掉除字符集以外的其他字符
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    self.orderNoLabel.text = newString;

    相关文章

      网友评论

        本文标题:iOS 字符串每4位用空格隔开

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