iOS string processing

I. use of NSCharacterSet

NSCharacterSet is a character set. With this class, you can operate strings more easily.

For example, "abcdefghijklmnffajkjawifa", we need to remove the "f" and "a" in this character. We will probably do this:

    NSString *str = @"abcdefghijklmnfwafajkfjawifa";
    NSInteger length = str.length;
    NSString *removeStr = @"af";
    NSMutableString *resultStr = [NSMutableString string];
    for (int i = 0; i < length; i ++) {
        NSString *indexStr = [str substringWithRange:NSMakeRange(i, 1)];
        if (![removeStr containsString:indexStr]) {
            [resultStr appendString:indexStr];

You can calculate the time complexity deliberately. It's really a piece of code that looks very fidgety.

If processing with NSCharacterSet:

    NSString *str = @"abcdefghijklmnfwafajkfjawifa";
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"af"];
    NSString *resultStr = [str stringByTrimmingCharactersInSet:set];

stringByTrimmingCharactersInSet: reduces the number of characters in the NSCharacterSet.

Creation of NSCharacterSet:

In addition to splicing string s, you can also use the following class methods to directly obtain a desired character set

/** Common shortcut collection  */ 
+ controlCharacterSet 
+ whitespaceCharacterSet //Blank space 
+ whitespaceAndNewlineCharacterSet //Spaces and line breaks 
+ decimalDigitCharacterSet //0-9 figure 
+ letterCharacterSet //All letters 
+ lowercaseLetterCharacterSet //Lowercase letters 
+ uppercaseLetterCharacterSet //Capital 
+ alphanumericCharacterSet //All numbers and letters (case insensitive) 
+ punctuationCharacterSet //Punctuation 
+ newlineCharacterSet //Line feed

/** URL Related shortcut collection  */ 
+ URLUserAllowedCharacterSet 
+ URLPasswordAllowedCharacterSet  
+ URLHostAllowedCharacterSet 
+ URLPathAllowedCharacterSet //Character set allowed by path
+ URLQueryAllowedCharacterSet //Character set allowed by parameter
+ URLFragmentAllowedCharacterSet 
II. rangeOfComposedCharacterSequencesForRange, rangeOfComposedCharacterSequenceAtIndex

The length of each Chinese or English in NSString is 1, but the length of an Emoji is 2 or 4. If substringToIndex is used, Emoji may be truncated, resulting in garbled code.

These two methods can obtain the complete characters in the current range or under the current index to avoid the occurrence of garbled code.

Tags: emoji

Posted on Fri, 06 Dec 2019 05:34:40 -0500 by bwcc