The number of digits is not enough to complement 0

NSString * STR = [NSString stringWithFormat:@"%02zd ",n]; // e.g: %02zd -->05 %03zd-->005Copy the code

Get Chinese characters pinyin

- (NSString *) pinyinFirstLetter:(NSString*)sourceString { NSMutableString *source = [sourceString mutableCopy]; CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO); // This line is tonal NSLog(@"..... >> %@",source); return source; }Copy the code

Uppercase

NSString *str = @"abcdefghijklmn"; NSString *resultStr; If (STR && STR. Length > 0) {resultStr = [STR stringByReplacingCharactersInRange: NSMakeRange (0, 1) withString: [[STR substringToIndex:1] capitalizedString]]; } NSLog(@"%@", resultStr);Copy the code

The beginning and end of a string

if([str hasPrefix:@"http"]){ 

} 

if([str hasSuffix:@".com"]){ 

} 
Copy the code

Long press to copy

[self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]]; } - (void)pasteBoard:(UILongPressGestureRecognizer *)longPress { if (longPress.state == UIGestureRecognizerStateBegan) {  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; Pasteboard. string = @" text to copy "; }Copy the code

Determines whether a String contains a String

[str containsString:@"abc"]; Or NSString *women = @"Hey you are boy?" ; If ([women containsString:@"boy"]) /*-- > If ([string hasPrefix:@"hello"]) {/*-- > If ([string hasPrefix:@"hello"]) {/*-- > If ([women containsString:@"boy"]) ([string hasSuffix:@"bitch"]) {Copy the code

Take a single character

/ / get the characters I nsstrings * chara = [string substringWithRange: NSMakeRange (I, 1));Copy the code

String inversion

- (NSString *)reverseWordsInString:(NSString *)str { NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length]; for (NSInteger i = str.length - 1; i >= 0 ; i --) { unichar ch = [str characterAtIndex:i]; [newString appendFormat:@"%c", ch]; } return newString; } or - (NSString*)reverseWordsInString:(NSString*) STR {NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length]; [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [reverString appendString:substring]; }]; return reverString; }Copy the code

Checks if the string is empty

+ (BOOL)isEqualToNil:(NSString *)str { return str.length <= 0 || [str isEqualToString:@""] || ! str; } - (BOOL)isExist { NSString *str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; return (str.length ! = 0); } #define Validity_Str(string) ((string! = nil) && (string.length>0))? YES:NO) // Check whether the string is validCopy the code

Add emoticons to your text

// Emoji, just add "\u+ emoji code" to the text of the label. Alabel. text = @" It's very nice today \uE337";Copy the code

Attachment: expression code books (in Unicode code, such as: U + 1 f604 – > U0001F604) punchdrunker. Making. IO/iOSEmoji/ta… ### Determine whether the input is Chinese

- (BOOL)isHasChineseWithStr:(NSString *)strFrom { for (int i=0; i<strFrom.length; i++) { NSRange range =NSMakeRange(i, 1); NSString * strFromSubStr=[strFrom substringWithRange:range]; const char *cStringFromstr = [strFromSubStr UTF8String]; If (strlen(cStringFromstr)==3) {return YES; } else if (strlen(cStringFromstr)==1) {// letter}} return NO; }Copy the code

Delimited string, delimited into an array of n elements

NSString*string =@"sdfsfsfs-dfsdf"; NSArray *array = [string componentsSeparatedByString:@"-"]; NSLog(@"array:%@",array); // The result is adfsfsfs and DFSDFCopy the code

Chinese character coding

NSstring *str = [chineseName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Copy the code

Remove the HTML tag

-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}
Copy the code

Dynamically calculate the string width and height

// dynamically calculate text width + (CGFloat)widthWithText:(NSString *)text andFontSize:(CGFloat)fontSize{CGRect rect = [text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil]; return rect.size.width; } // dynamically calculate text height + (CGFloat)heightWithText:(NSString *)text andFontSize:(CGFloat)fontSize{CGRect rect = [text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 100, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil]; return rect.size.height; }Copy the code

To calculate the length of a string, one Chinese character counts as two characters

-(NSUInteger) unicodeLengthOfString: (NSString *) text { NSUInteger asciiLength = 0; for (NSUInteger i = 0; i < text.length; i++) { unichar uc = [text characterAtIndex: i]; asciiLength += isascii(uc) ? 1:2; } return asciiLength; }Copy the code

String base64 encoding

+ (NSString *)base64StringFromText:(NSString *)text { NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64String = [data base64EncodedStringWithOptions:0]; return base64String; } /* decode */ + (NSString *)textFromBase64String:(NSString *)base64 {NSData *data = [[NSData alloc] initWithBase64EncodedString:base64 options:0]; NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return text; }Copy the code

String decoding

NSString *result = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Copy the code

Utf-8 encoding of strings: UtF-8 format is output

[STR stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];Copy the code

String encoding

NSString *urll = self.URL;
    urll = [urll stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"%<>[\\]^`{|}\"]+"].invertedSet];
Copy the code
/ / we usually use this method processing stringByAddingPercentEscapesUsingEncoding but really want to this method will not deal with the special symbol of/and &, So in that case, we need to do the following method: @implementation NSString (NSString_Extended) - (NSString *) urlenCode {NSMutableString *output = [NSMutableString string]; const unsigned char *source = (const unsigned char *)[self UTF8String]; int sourceLen = strlen((const char *)source); for (int i = 0; i < sourceLen; ++i) { const unsigned char thisChar = source[i]; if (thisChar == ' '){ [output appendString:@"+"]; } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || (thisChar >= 'a' && thisChar <= 'z') || (thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= '0' && thisChar <= '9')) { [output appendFormat:@"%c", thisChar]; } else { [output appendFormat:@"%%%02X", thisChar]; } } return output; }Copy the code

Dictionary to string

SData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Copy the code

Json string to dictionary

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];  If (err) {NSLog(@" JSON parsing failed: %@",err); return nil; } return dic; }Copy the code

Model array to JSON string

/ / array first model dictionary array NSArray * dictArray = [PDcycleImageItem mj_keyValuesArrayWithObjectArray: _extraCycleImgArray]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictArray options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];Copy the code

String substitution

NSString*str =@"12345678";
NSString*Str2 = [str stringByReplacingOccurrencesOfString:@"345"withString:@"543"];
Copy the code

Remove all whitespace, line breaks

Resolve JSON string formatting errors.

+ (NSString *)removeSpaceAndNewline:(NSString *)str {
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
Copy the code

String splicing correlation

1. If count is less than 2 bits, use 0 to complete it first (2 represents the total output number). NSInteger count = 5; NSString *string = [NSString stringWithFormat:@"%02zd",count]; 2. Add percent sign % NSInteger count = 50; //% is a special symbol. If you use % in NSString, you should write NSString *string = [NSString String WithFormat:@"%zd%%",count]; 3. Double quotation marks: if you use "NSString", you need to escape NSInteger count = 50; NSString *string = [NSString stringWithFormat:@"%zd\"",count]; // The output is: 50"Copy the code

Gets the number in the string

NSString * SSSTR = @" NSString * SSSTR = @"; NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet]; float num =[[ssstr stringByTrimmingCharactersInSet:nonDigits] floatValue]; NSLog(@" num %.1f ",num);Copy the code

The string after a string is truncated

NSRange range = [aString rangeOfString:@"redirect="]; / / now get to intercept string position nsstrings * rurl = [aString substringFromIndex: range. The location]. // intercepts the string //-- returns the result containing the string: redirect=Copy the code

Intercepts the string between two specified strings

Nsstrings * string = @ "< a href = \ \" HTTP "> this is to capture the content of the < / a >"; NSRange startRange = [string rangeOfString:@"\">"]; NSRange endRange = [string rangeOfString:@"</"]; NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length); NSString *result = [string substringWithRange:range]; NSLog(@"%@",result);Copy the code

Gets the URL in the string

The application of regular expressions

+ (NSArray *)getURLFromString:(NSString *)string { NSError *error; / / can identify the url of the regular expression nsstrings * regulaStr = @ "(HTTP [s] {0, 1} | (FTP) : / / / a - zA - Z0-9 \ \. \ \ -] + \ \. ([a zA - Z] {2, 4}) (: \ \ d +)? (/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?) | (WWW. [a zA - Z0-9 \ \. \ \ -] + \ \. ([a zA - Z] {2, 4}) (: \ \ d +)? (/ [a - zA - Z0-9 \ \. \ \ ~! @ # $% ^ & * +? : _ / = < >] *?) "; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])]; NSMutableArray *arr=[[NSMutableArray alloc] init]; for (NSTextCheckingResult *match in arrayOfAllMatches){ NSString* substringForMatch; substringForMatch = [string substringWithRange:match.range]; [arr addObject:substringForMatch]; } return arr; }Copy the code

Intercepts a substring of the specified range

NSString * STR = @" It's a nice day today. We don't have classes this afternoon. NSString *str1 = [STR substringFromIndex:17]; NSString *str1 = [STR substringFromIndex:17]; NSString *str2 = [STR substringToIndex:7]; NSRange = {7, 10}; NSString *str3 = [str substringWithRange:range]; NSRange range1 = [STR rangeOfString:@" we don't have classes in the afternoon "]; NSString *str4 = [str substringFromIndex:range1.location]; NSUInteger loc1 = [STR rangeOfString:@"/"]. Location + 1; NSString *result = [str substringFromIndex:loc1];Copy the code

Sets label rich text

/ / create Attributed NSMutableAttributedString * noteStr = [[NSMutableAttributedString alloc] initWithString: _label. Text]; NSUInteger firstLoc = [[noteStr String] rangeOfString:@" "]. Location + 1; NSUInteger secondLoc = [[noteStr String] rangeOfString:@" "].Location; NSRange range = NSMakeRange(firstLoc, secondLoc - firstLoc); / / change the color [noteStr addAttribute: NSForegroundColorAttributeName value: [UIColor greenColor] range: the range]; / / change the font size and type [noteStr addAttribute: NSFontAttributeName value: [UIFont fontWithName: @ "Helvetica - BoldOblique" size: 27] range:range]; [_label setAttributedText:noteStr]; // Add a rich text attribute to the labelCopy the code

Changes the color of the specified substring, etc

NSString *str0 = @" It's a beautiful day today, let's go play, ok?" ; NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str0]; NSRange range0 = [str0 rangeOfString:@" very good "]; [attributedStr addAttribute:NSForegroundColorAttributeName value:MainThemeBlue range:range0]; _contentLb.attributedText = attributedStr;Copy the code

Add pictures to text

// instantiate a Lable... . / / create a rich text NSMutableAttributedString * attri = [[NSMutableAttributedString alloc] initWithString: @ "timeout fined $24 / hour"]. NSTextAttachment *attch = [NSTextAttachment alloc] init]; attch.image = [UIImage imageNamed:@"parking_caveat_normal"]; attch.bounds = CGRectMake(0, 0, 15, 15); / / create a picture of a rich text NSAttributedString * string = [NSAttributedString attributedStringWithAttachment: attch]; / / behind the text add images [attri appendAttributedString: string]; Or / / in which a text subscript add images [attri insertAttributedString: string atIndex: 0]; // Use the label attributedText attribute to use the rich text lable.attributedText = attri;Copy the code

Continuously updated… .