iOS 字符串的常用处理方法

字符串反转

#pragma mark----- 字符串处理
- (NSString*)reverseWords {
    NSMutableString *reverString = [NSMutableString stringWithCapacity:self.length];
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [reverString appendString:substring];
    }];
    return reverString;
}

字符串转拼音

- (NSString *)transformToPhonetic {
    
    NSMutableString *pinyin = [self mutableCopy];
    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    
    return pinyin;
}

首字母大写

- (NSString *)capitalFirstLetter{
    NSString *resultStr;
    if (self && self.length > 0) {
        resultStr = [self stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[self substringToIndex:1] capitalizedString]];
    }
    return resultStr;
}

删除所有空格

- (NSString *)deleteAllWhiteSpace{
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

删除首尾空格

- (NSString *)deleteFirstAndLastWhiteSpace{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

使用正则替换某一段文字(空格正则为\\s,可去除全角和半角,不包括tab)

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|>|>)" options:NSRegularExpressionCaseInsensitive error:nil];//
    
titleText = [regex stringByReplacingMatchesInString:titleText
                                                 options:0
                                                   range:NSMakeRange(0, titleText.length)
                                            withTemplate:@""];

计算字符串中重复字符出现的次数

NSString *string = @"ABKJFDRFIUEROFDVFDLPEOFPEM";
NSArray *arr = [string componentsSeparatedByString:@"D"];
NSLog(@"==========%lu",arr.count-1);

全角空格转半角

- (NSString *)replaceSpecialWhitespace{
    NSMutableString *convertedString = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)convertedString, NULL, kCFStringTransformFullwidthHalfwidth, false);
    return [NSString stringWithString:convertedString];
}

半角空格转全角

- (NSString *)replaceNormalWhiteSpace{
    NSMutableString *convertedString = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)convertedString, NULL, kCFStringTransformHiraganaKatakana, false);
    return [NSString stringWithString:convertedString];
}





点击可查看应用中更多实用的小工具

你可能感兴趣的:(iOS小知识,iOS)