Dependency: NSString: NSObject: Foundation
NSString is an immutable string object. This does not mean that the value of the variable declared by this object is immutable, but that after initialization, you cannot change the value in the memory allocated by this variable, but you can reallocate the memory space of this variable. NSMutableString is mutable, which means you can append its memory space or modify the value in the memory space allocated by it.
OC string
NSString *str1 = @"hello world"; NSString *str2 =[ [NSString alloc]initWithFormat:@"xiaoming %@",str1];
C language string
char *str = "hello world"; OC compatible C string
Common methods:
NSString
- NSString initialization
- String length calculation (length method)
- string comparison
- String judgment (prefix and suffix)
- Intercept string
- NSString string replacement and case conversion
- Concatenate string
- Split string
- Traversal of strings
- Remove leading and trailing spaces from string
- String conversion
NSMutableString variable string
- Initialization
- increase
- Delete
- change
- check
NSString
NSString initialization
//1.NSString initialization //Object method "-" //(1) declare a constant string NSString *str1 = @"hello world"; //(2) produce a new string by knowing the string NSString *str2 = [[NSString alloc]initWithString:str1]; //(3) generate an OC with a c language string NSString *str3 = [[NSString alloc]initWithUTF8String:"hello world"]; //(4) format and create a string to generate a new string, which can be spliced NSString *str4 =[ [NSString alloc]initWithFormat:@"xiaoming %@",str1]; //(5) theoretical usage of initialization first NSString *str5 = [NSString new]; str5 = @"hello world"; NSLog(@"str1 = %@",str1); NSLog(@"str2 = %@",str2); NSLog(@"str3 = %@",str3); NSLog(@"str4 = %@",str4); NSLog(@"str5 = %@",str5); //Class method "+" creation NSString *str6 = [NSString stringWithString:str1]; NSString *str7 = [NSString stringWithUTF8String:"hello world"]; NSString *str8 = [NSString stringWithFormat:@"xiaoming %@",str1]; NSLog(@"str6 = %@",str6); NSLog(@"str7 = %@",str7); NSLog(@"str8 = %@",str8);
Execution result:
2019-05-21 15:29:15.368229+0800 MGNSString[419:28050] str1 = hello world
2019-05-21 15:29:15.368273+0800 MGNSString[419:28050] str2 = hello world
2019-05-21 15:29:15.368287+0800 MGNSString[419:28050] str3 = hello world
2019-05-21 15:29:15.368305+0800 MGNSString[419:28050] str4 = xiaoming hello world
2019-05-21 15:29:15.368322+0800 MGNSString[419:28050] str5 = hello world
2019-05-21 15:29:15.368345+0800 MGNSString[419:28050] str6 = hello world
2019-05-21 15:29:15.368357+0800 MGNSString[419:28050] str7 = hello world
2019-05-21 15:29:15.368368+0800 MGNSString[419:28050] str8 = xiaoming hello world
String length calculation (length method)
//2. String length calculation (length method) NSString *str9 = @"hello world"; NSUInteger len = [str9 length]; NSLog(@"String length :%ld",len); //It must be%ld.
Execution result:
2019-05-21 15:29:15.368398+0800 MGNSString[419:28050] string length: 11
string comparison
//3. String comparison NSString *str10 = @"hello world"; NSString *str11 = @"hello"; //Determine whether two strings are the same BOOL flag1 = [str10 isEqualToString:str11]; NSLog(@"flag1 = %d",flag1); //Include 1 or not BOOL flag2 = [str10 containsString:str11]; NSLog(@"flag2 = %d",flag2); //Include 2 or not NSRange range1 = [str10 rangeOfString:str11]; if (range1.location != NSNotFound) { NSLog(@"Include string"); } else{ NSLog(@"No strings"); } //Sort by size //NSComparisonResult is an enumeration, NSOrderedAscending (ascending = 1), nsorderedsame (same = 0), nsordereddescending (descending = 1) can be judged NSComparisonResult result1 = [str10 compare:str11]; NSLog(@"result1 = %ld",result1); if (result1 == NSOrderedAscending) { NSLog(@"Ascending order"); } else if(result1 == NSOrderedSame) { NSLog(@"identical"); } else if(result1 == NSOrderedDescending) { NSLog(@"Descending order"); } /*compare Three common conditions: NSCaseInsensitiveSearch: case insensitive NSLiteralSearch: for full comparison, case sensitive (default) NSNumericSearch: To compare the number of characters in a string, rather than the character value */ //Multiple comparison conditions can be added NSComparisonResult result2 = [str10 compare:str11 options:NSCaseInsensitiveSearch|NSNumericSearch]; NSLog(@"result2 = %ld",result2);
Execution result:
2019-05-21 15:29:15.368432+0800 MGNSString[419:28050] flag1 = 0
2019-05-21 15:29:15.368481+0800 MGNSString[419:28050] flag2 = 1
2019-05-21 15:29:15.368500+0800 MGNSString[419:28050] Include string
2019-05-21 15:29:15.368514+0800 MGNSString[419:28050] result1 = 1
2019-05-21 15:29:15.368540+0800 MGNSString[419:28050] Descending order
2019-05-21 15:29:15.368572+0800 MGNSString[419:28050] result2 = 1
String judgment (prefix and suffix)
//4. String judgment (prefix and suffix) //NSString pre suffix check NSString *url = @"https://ios,itcast.cn/xxxxx.jpg"; //Check whether the prefix of a string starts with http: / / or https: / / if ([url hasPrefix:@"http://"]||[url hasPrefix:@"https://"]) { NSLog(@"This is a website"); }else{ NSLog(@"This is not a website"); } //Check whether the suffix of a string is. jpg if ([url hasSuffix:@".jpg"]) { NSLog(@"This is a jpg picture"); }else{ NSLog(@"This is not a jpg picture"); }
Execution result:
2019-05-21 15:29:15.368599+0800 MGNSString[419:28050] this is a website
2019-05-21 15:29:15.368613+0800 MGNSString[419:28050] this is a jpg picture
Intercept string
//5. Intercept string //Get new string by cutting string //In the front NSString *str12 = @"hello world"; NSString *str13 = [str12 substringToIndex:5]; NSLog(@"str13 = %@",str13); //In the back. NSString *str14 = [str12 substringFromIndex:5]; NSLog(@"str14 = %@",str14); //Specified range interception NSString *str15 = [str1 substringWithRange:NSMakeRange(5, 2)];//6 start backward 2 bits NSLog(@"str15 = %@",str15); //Position space in string does not count as position range structure variable NSRange range2 = [str1 rangeOfString:@"world"]; NSLog(@"%lu %lu",(unsigned long)range2.location,(unsigned long)range2.length);
Execution result:
2019-05-21 15:29:15.368676+0800 MGNSString[419:28050] str13 = hello
2019-05-21 15:29:15.368704+0800 MGNSString[419:28050] str14 = world
2019-05-21 15:29:15.368727+0800 MGNSString[419:28050] str15 = w
2019-05-21 15:29:15.368741+0800 MGNSString[419:28050] 6 5
NSString string replacement and case conversion
//6.NSString string replacement and case conversion //String replacement NSString *str16 = @"hello world"; NSString *str17 = [str16 stringByReplacingOccurrencesOfString:@"world" withString:@"world"]; NSLog(@"str17 = %@",str17); //Bit by bit substitution NSString *str18 = [str16 stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@"Hello"]; NSLog(@"str18 = %@", str18); NSString *str19 = @"abcdABCD1234"; //Turn capitalization NSLog(@"Capitalization str18 = %@",[str19 uppercaseString]); //Turn lowercase NSLog(@"A lowercase letter str18 = %@",[str19 lowercaseString]); //The first letter becomes uppercase and all other letters become lowercase NSLog(@"The first letter becomes uppercase and all other letters become lowercase str18 = %@",[str19 capitalizedString]);
Execution result:
2019-05-21 15:29:15.368832+0800 MGNSString[419:28050] str17 = hello World
2019-05-21 15:29:15.368923+0800 MGNSString[419:28050] str18 = Hello world
2019-05-21 15:29:15.369001+0800 MGNSString[419:28050] capital str18 = ABCDABCD1234
2019-05-21 15:29:15.369028+0800 MGNSString[419:28050] small str18 = abcdabcd1234
2019-05-21 15:29:15.369053+0800 MGNSString[419:28050] initial becomes upper case, other letters become lowercase str18 = Abcdabcd1234
Concatenate string
//7. Splicing string NSString *str20 = @"Hello"; //String splicing NSString *str21 = [str20 stringByAppendingString:@"world"]; NSLog(@"str21 = %@",str21); //Path splicing will automatically add "/" before the string to become the full path NSString *str22 = [str20 stringByAppendingPathComponent:@"Desktop"]; NSLog(@"str22 = %@",str22);
Execution result:
2019-05-21 15:29:15.369099+0800 MGNSString[419:28050] str21 = Hello World
2019-05-21 15:29:15.369179+0800 MGNSString[419:28050] str22 = hello / Desktop
Split string
//8. Split string NSString *str23 = @"I-yes-Who?-I-stay-Where?"; //Split - as base NSArray *arr1 = [str23 componentsSeparatedByString:@"-"]; for (NSString *str in arr1) { NSLog(@"%@", str); } //Splits a string with a specified string and returns an array NSString *str24 = @"1,2,3,4,5,6"; NSArray *arr2 = [str24 componentsSeparatedByString:@","]; NSLog(@"array:%@ \n The number of arrays is%zd",arr2,arr2.count); //Take out the number part of the string "123| 456| 789| 000" to form a new string output //Note: only variable string NSMutableString has this method NSMutableString *mtStr = [NSMutableString stringWithString:@"123|456|789|000"]; [mtStr replaceOccurrencesOfString:@"|" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, mtStr.length)]; NSLog(@"mtStr = %@",mtStr);
Execution result:
May 21, 2019 15:29:15.369303 + 0800 mgnsstring [419:28050] me
2019-05-21 15:29:15.369327+0800 MGNSString[419:28050] Yes
2019-05-21 15:29:15.369349+0800 MGNSString[419:28050] who?
May 21, 2019 15:29:15.369390 + 0800 mgnsstring [419:28050] me
2019-05-21 15:29:15.369417+0800 MGNSString[419:28050] at
2019-05-21 15:29:15.369439+0800 MGNSString[419:28050] where?
2019-05-21 15:29:15.369802+0800 MGNSString[419:28050] array:(
1,
2,
3,
4,
5,
6
)
The number of arrays is 6
2019-05-21 15:29:15.369826+0800 MGNSString[419:28050] mtStr = 123456789000
Traversal of strings
//9. Traversal of strings NSString *str25 = @"abc\ndef\n123"; // Print line by line [str25 enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) { NSLog(@"line:%@",line); }];
Execution result:
2019-05-21 15:29:15.369927+0800 MGNSString[419:28050] line:abc
2019-05-21 15:29:15.369953+0800 MGNSString[419:28050] line:def
2019-05-21 15:29:15.369978+0800 MGNSString[419:28050] line:123
Remove leading and trailing spaces from string
//10.NSString remove leading and trailing spaces /* controlCharacterSet Go to the beginning and the end lowercaseLetterCharacterSet Lowercase letter without head and tail uppercaseLetterCharacterSet To close capital letters + (NSCharacterSet *)characterSetWithRange:(NSRange)aRange;Go to the beginning and the end to make position letters */ NSString *str26 = @" hello world "; NSString *str27 = [str26 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//Returns the stripped string NSLog(@"str27 = %@",str27);
Execution result:
2019-05-21 15:29:15.370010+0800 MGNSString[419:28050] str27 = hello world
String conversion
//11. String conversion NSString *str28 = @"1234"; int value1 = [str28 intValue]; float value2 = [str28 floatValue]; double value3 = [str28 doubleValue]; BOOL value4 = [str28 boolValue]; NSLog(@"value1 = %d| value2 = %f| value3 = %lf| value4 = %d| ",value1,value2,value3,value4); //Conversion between OC string and C string char *s1 = "hello world"; NSString *str29 = [NSString stringWithUTF8String:s1]; NSLog(@"str29 = %@",str29); const char *s2 = [str29 cStringUsingEncoding:NSASCIIStringEncoding]; const char *s3 = [str29 UTF8String]; NSLog(@"s2 = %s",s2); NSLog(@"s3 = %s",s3);
Execution result:
2019-05-21 15:29:15.370067+0800 MGNSString[419:28050] value1 = 1234| value2 = 1234.000000| value3 = 1234.000000| value4 = 1|
2019-05-21 15:29:15.370090+0800 MGNSString[419:28050] str29 = hello world
2019-05-21 15:29:15.370116+0800 MGNSString[419:28050] s2 = hello world
2019-05-21 15:29:15.370201+0800 MGNSString[419:28050] s3 = hello world
NSMutableString
//II. NSMutableString //The NSMutableString class is created in the same way as NSString, but it needs to be noted that NSMutableString cannot be created in the direct way, because the strings created in the direct way are in the constant pool, and the values in the constant pool are immutable, so they cannot be created. At the same time, the strings created by initWithString are not in the constant pool . NSString *str30 = @"hello world"; //NSMutableString *mtAtr1 = @ "error initialization, variable" NSMutableString *mtAtr1 = [[NSMutableString alloc]initWithString:str30]; NSMutableString *mtAtr2 = [NSMutableString stringWithString:str30]; NSMutableString *mtAtr3 = [[NSMutableString alloc]initWithUTF8String:"hello"]; NSMutableString *mtAtr4 = [NSMutableString stringWithUTF8String:"hello"]; NSMutableString *mtAtr5 = [[NSMutableString alloc]initWithFormat:@"%@ world",str30]; NSMutableString *mtAtr6 = [NSMutableString stringWithFormat:@"%@ world",str30]; NSLog(@"mtAtr1 = %@",mtAtr1); NSLog(@"mtAtr2 = %@",mtAtr2); NSLog(@"mtAtr3 = %@",mtAtr3); NSLog(@"mtAtr4 = %@",mtAtr4); NSLog(@"mtAtr5 = %@",mtAtr5); NSLog(@"mtAtr6 = %@",mtAtr6); //Adding and appending strings will not generate new objects [mtAtr1 appendString:@"xxxx"]; NSLog(@"mtAtr1 = %@",mtAtr1); [mtAtr1 appendFormat:@"%@,%c",str30,'o']; NSLog(@"mtAtr1 = %@",mtAtr1); [mtAtr1 insertString:@"###" atIndex:5]; NSLog(@"mtAtr1 = %@",mtAtr1); //Delete NSMutableString *mtAtr7 = [NSMutableString stringWithString:@"hello"]; [mtAtr7 deleteCharactersInRange:NSMakeRange(1, 3)]; NSLog(@"mtAtr7 = %@",mtAtr7); //Replacement NSMutableString *mtAtr8 = [NSMutableString stringWithString:@"hello"]; NSRange ranges = [mtAtr8 rangeOfString:@"ll"];//First, find out the range of the string to be replaced [mtAtr8 replaceCharactersInRange:ranges withString:@"ee"]; NSLog(@"mtAtr8 = %@",mtAtr8); //check NSString *str31 = @"can you \n speak English"; NSString *str32 = @"\n"; //Search the str1 string to see if there is any if ([str31 rangeOfString:str32].location != NSNotFound) { NSLog(@"This string contains\n"); } //The first parameter of rangeOfString is the string to be searched, and the second is the character to be searched //NSNotFound indicates that a content or item of the requested operation is not found or does not exist
Execution result:
2019-05-21 15:29:15.370244+0800 MGNSString[419:28050] mtAtr1 = hello world
2019-05-21 15:29:15.370257+0800 MGNSString[419:28050] mtAtr2 = hello world
2019-05-21 15:29:15.370268+0800 MGNSString[419:28050] mtAtr3 = hello
2019-05-21 15:29:15.370279+0800 MGNSString[419:28050] mtAtr4 = hello
2019-05-21 15:29:15.370290+0800 MGNSString[419:28050] mtAtr5 = hello world world
2019-05-21 15:29:15.370322+0800 MGNSString[419:28050] mtAtr6 = hello world world
2019-05-21 15:29:15.370335+0800 MGNSString[419:28050] mtAtr1 = hello worldxxxx
2019-05-21 15:29:15.370351+0800 MGNSString[419:28050] mtAtr1 = hello worldxxxxhello world,o
2019-05-21 15:29:15.370365+0800 MGNSString[419:28050] mtAtr1 = hello### worldxxxxhello world,o
2019-05-21 15:29:15.370379+0800 MGNSString[419:28050] mtAtr7 = ho
2019-05-21 15:29:15.370425+0800 MGNSString[419:28050] mtAtr8 = heeeo
2019-05-21 15:29:15.370443+0800 MGNSString[419:28050] This string contains
NSString.h Apple technical document translation
/* NSString.h Copyright (c) 1994-2018, Apple Inc. All rights reserved. Apple Copyright (c) 1994-2018 all rights reserved. */ /* An NSString object encodes a Unicode-compliant text string, represented as a sequence of UTF–16 code units. All lengths, character indexes, and ranges are expressed in terms of UTF–16 code units, with index values starting at 0. The length property of an NSString returns the number of UTF-16 code units in an NSString, and the characterAtIndex: method retrieves a specific UTF-16 code unit. These two "primitive" methods provide basic access to the contents of a string object. NSString The object encodes a unicode compliant text string that is represented as a sequence of UTF-16 code units. All length, character index, and range are represented in UTF-16 code units, with index values starting at 0. The length property of NSString returns the number of UTF-16 code units in NSString. The characterAtIndex: method retrieves a specific UTF-16 code unit. These two "basic" methods provide basic access to the content of the string object. Most use of strings, however, is at a higher level, with the strings being treated as single entities: Using the APIs in NSString, you can compare strings against one another, search them for substrings, combine them into new strings, and so on. In cases where locale settings may make a difference, use the localized... API variants to perform the operations using the current user's locale, or use the locale: variants that take an explicit NSLocale argument. However, most use of strings is at a higher level, and strings are treated as a single entity: using the API in NSString, you can compare strings with each other, search their substrings, combine them into new strings, and so on. In cases where locale settings may have an impact, use localized An API variation that uses the locale of the current user to perform the operation, or a variation that uses locale: to accept the explicit NSLocale parameter. If you do need to access individual characters in a string, you need to consider whether you want to access the individual UTF-16 code points (referred to as "characters" in APIs, and represented with the "unichar" type), or human-readable characters (referred to as "composed character sequences" or "grapheme clusters"). Composed character sequences can span multiple UTF-16 characters, when representing a base letter plus an accent, for example, or Emoji. If you do need to access a single character in a string, you need to consider whether you want to access a single UTF-16 code point (referred to in the api as a "character" and represented with a "unichar" type), or a human readable character (referred to as a "combined character sequence" or "grapheme cluster"). A combined character sequence can span multiple UTF-16 characters, for example, when representing a basic letter with an accent or emoticon. To access composed character sequences, use APIs such as rangeOfComposedCharacterSequenceAtIndex:, or enumerate the whole or part of the string with enumerateSubstringsInRange:options:usingBlock:, supplying NSStringEnumerationByComposedCharacterSequences as the enumeration option. To access the combined character sequence, you can use an api such as rangeOfComposedCharacterSequenceAtIndex: or enumeratessubstringsinrange: options: usingblock: to enumerate the whole or part of the string, and provide NSStringEnumerationByComposedCharacterSequences as the enumeration option. For instance, to extract the composed character sequence at a given index (where index is a valid location in the string, 0..length-1): For example, extract a sequence of combined characters at a given index, where index is a valid position in the string, 0.. length-1: NSString *substr = [string substringWithRange:[string rangeOfComposedCharacterSequenceAtIndex:index]]; And to enumerate composed character sequences in a string: To enumerate the sequence of characters in a string: [string enumerateSubstringsInRange:NSMakeRange(0, string.length) // enumerate the whole range of the string options:NSStringEnumerationByComposedCharacterSequences // by composed character sequences usingBlock:^(NSString * substr, NSRange substrRange, NSRange enclosingRange, BOOL *stop) { ... use substr, whose range in string is substrRange ... }]; NSStrings can be immutable or mutable. The contents of an immutable string is defined when it is created and subsequently cannot be changed. To construct and manage a string that can be changed after it has been created, use NSMutableString, which is a subclass of NSString. NSString It can be either immutable or variable. The contents of an immutable string are defined at creation time and cannot be changed. To construct and manage a string that can be changed after creation, use NSMutableString, which is a subclass of NSString. An NSString object can be initialized using a number of ways: From a traditional (char *) C-string, a sequence of bytes, an NSData object, the contents of an NSURL, etc, with the character contents specified in a variety of string encodings, such as ASCII, ISOLatin1, UTF–8, UTF–16, etc. NSString Objects can be initialized in many ways: from the traditional (char *) C-string, byte sequence, NSData object, the content of NSURL, and so on, using the character content specified in various string encodings, such as ASCII, ISOLatin1, UTF-8, UTF-16, and so on. */ /* The unichar type represents a single UTF-16 code unit in an NSString. Although many human-readable characters are representable with a single unichar, some such as Emoji may span multiple unichars. See discussion above. unichar Type represents a single UTF-16 code unit in NSString. Although many human readable characters can be represented by one unified character, some characters (such as emoticons) may span multiple unified characters. See discussion above. */ typedef unsigned short unichar; #import <limits.h> #import <Foundation/NSObject.h> #import <Foundation/NSRange.h> #import <Foundation/NSItemProvider.h> #import <stdarg.h> @class NSData, NSArray<ObjectType>, NSDictionary<KeyType, ObjectType>, NSCharacterSet, NSURL, NSError, NSLocale; NS_ASSUME_NONNULL_BEGIN /* These options apply to the various search/find and comparison methods (except where noted). */ typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) { NSCaseInsensitiveSearch = 1, NSLiteralSearch = 2, /* Exact character-by-character equivalence */ NSBackwardsSearch = 4, /* Search from end of source string */ NSAnchoredSearch = 8, /* Search is limited to start (or end, if NSBackwardsSearch) of source string */ NSNumericSearch = 64, /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */ NSDiacriticInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, /* If specified, ignores diacritics (o-umlaut == o) */ NSWidthInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256, /* If specified, ignores width differences ('a' == UFF41) */ NSForcedOrderingSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */ NSRegularExpressionSearch API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024 /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */ }; /* Note that in addition to the values explicitly listed below, NSStringEncoding supports encodings provided by CFString. See CFStringEncodingExt.h for a list of these encodings. See CFString.h for functions which convert between NSStringEncoding and CFStringEncoding. */ typedef NSUInteger NSStringEncoding; NS_ENUM(NSStringEncoding) { NSASCIIStringEncoding = 1, /* 0..127 only */ NSNEXTSTEPStringEncoding = 2, NSJapaneseEUCStringEncoding = 3, NSUTF8StringEncoding = 4, NSISOLatin1StringEncoding = 5, NSSymbolStringEncoding = 6, NSNonLossyASCIIStringEncoding = 7, NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */ NSISOLatin2StringEncoding = 9, NSUnicodeStringEncoding = 10, NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */ NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */ NSWindowsCP1253StringEncoding = 13, /* Greek */ NSWindowsCP1254StringEncoding = 14, /* Turkish */ NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */ NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */ NSMacOSRomanStringEncoding = 30, NSUTF16StringEncoding = NSUnicodeStringEncoding, /* An alias for NSUnicodeStringEncoding */ NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */ NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */ NSUTF32StringEncoding = 0x8c000100, NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */ NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */ }; typedef NS_OPTIONS(NSUInteger, NSStringEncodingConversionOptions) { NSStringEncodingConversionAllowLossy = 1, NSStringEncodingConversionExternalRepresentation = 2 }; @interface NSString : NSObject <NSCopying, NSMutableCopying, NSSecureCoding> #pragma mark *** String funnel methods *** /* NSString primitives. A minimal subclass of NSString just needs to implement these two, along with an init method appropriate for that subclass. We also recommend overriding getCharacters:range: for performance. */ @property (readonly) NSUInteger length; - (unichar)characterAtIndex:(NSUInteger)index; /* The initializers available to subclasses. See further below for additional init methods. */ - (instancetype)init NS_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; @end @interface NSString (NSStringExtensionMethods) #pragma mark *** Substrings *** /* To avoid breaking up character sequences such as Emoji, you can do: [str substringFromIndex:[str rangeOfComposedCharacterSequenceAtIndex:index].location] [str substringToIndex:NSMaxRange([str rangeOfComposedCharacterSequenceAtIndex:index])] [str substringWithRange:[str rangeOfComposedCharacterSequencesForRange:range] */ - (NSString *)substringFromIndex:(NSUInteger)from; - (NSString *)substringToIndex:(NSUInteger)to; - (NSString *)substringWithRange:(NSRange)range; // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences - (void)getCharacters:(unichar *)buffer range:(NSRange)range; // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences #pragma mark *** String comparison and equality *** /* In the compare: methods, the range argument specifies the subrange, rather than the whole, of the receiver to use in the comparison. The range is not applied to the search string. For example, [@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares "A" to "ABC", not "A" to "A", and will return NSOrderedAscending. It is an error to specify a range that is outside of the receiver's bounds, and an exception may be raised. */ - (NSComparisonResult)compare:(NSString *)string; - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare; - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice. - (NSComparisonResult)caseInsensitiveCompare:(NSString *)string; - (NSComparisonResult)localizedCompare:(NSString *)string; - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string; /* localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings. */ - (NSComparisonResult)localizedStandardCompare:(NSString *)string API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); - (BOOL)isEqualToString:(NSString *)aString; #pragma mark *** String searching *** /* These perform locale unaware prefix or suffix match. If you need locale awareness, use rangeOfString:options:range:locale:, passing NSAnchoredSearch (or'ed with NSBackwardsSearch for suffix, and NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch if needed) for options, NSMakeRange(0, [receiver length]) for range, and [NSLocale currentLocale] for locale. */ - (BOOL)hasPrefix:(NSString *)str; - (BOOL)hasSuffix:(NSString *)str; - (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask; /* Simple convenience methods for string searching. containsString: returns YES if the target string is contained within the receiver. Same as calling rangeOfString:options: with no options, thus doing a case-sensitive, locale-unaware search. localizedCaseInsensitiveContainsString: is the case-insensitive variant which also takes the current locale into effect. Starting in 10.11 and iOS9, the new localizedStandardRangeOfString: or localizedStandardContainsString: APIs are even better convenience methods for user level searching. More sophisticated needs can be achieved by calling rangeOfString:options:range:locale: directly. */ - (BOOL)containsString:(NSString *)str API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* The following two are the most appropriate methods for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. As with other APIs, "standard" in the name implies "system default behavior," so the exact list of search options applied may change over time. If you need more control over the search options, please use the rangeOfString:options:range:locale: method. You can pass [NSLocale currentLocale] for searches in user's locale. */ - (BOOL)localizedStandardContainsString:(NSString *)str API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); - (NSRange)localizedStandardRangeOfString:(NSString *)str API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* These methods perform string search, looking for the searchString within the receiver string. These return length==0 if the target string is not found. So, to check for containment: ([str rangeOfString:@"target"].length > 0). Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such. Note that the first three methods do not take locale arguments, and perform the search in a non-locale aware fashion, which is not appropriate for user-level searching. To do user-level string searching, use the last method, specifying locale:[NSLocale currentLocale], or better yet, use localizedStandardRangeOfString: or localizedStandardContainsString:. The range argument specifies the subrange, rather than the whole, of the receiver to use in the search. It is an error to specify a range that is outside of the receiver's bounds, and an exception may be raised. */ - (NSRange)rangeOfString:(NSString *)searchString; - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask; - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch; - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); /* These return the range of the first character from the set in the string, not the range of a sequence of characters. The range argument specifies the subrange, rather than the whole, of the receiver to use in the search. It is an error to specify a range that is outside of the receiver's bounds, and an exception may be raised. */ - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch; - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index; - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); - (NSString *)stringByAppendingString:(NSString *)aString; - (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); #pragma mark *** Extracting numeric values *** /* The following convenience methods all skip initial space characters (whitespaceSet) and ignore trailing characters. They are not locale-aware. NSScanner or NSNumberFormatter can be used for more powerful and locale-aware parsing of numbers. */ @property (readonly) double doubleValue; @property (readonly) float floatValue; @property (readonly) int intValue; @property (readonly) NSInteger integerValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); @property (readonly) long long longLongValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); @property (readonly) BOOL boolValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); // Skips initial space characters (whitespaceSet), or optional -/+ sign followed by zeroes. Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9. It ignores any trailing characters. #pragma mark *** Case changing *** /* The following three return the canonical (non-localized) mappings. They are suitable for programming operations that require stable results not depending on the user's locale preference. For locale-aware case mapping for strings presented to users, use the "localized" methods below. */ @property (readonly, copy) NSString *uppercaseString; @property (readonly, copy) NSString *lowercaseString; @property (readonly, copy) NSString *capitalizedString; /* The following three return the locale-aware case mappings. They are suitable for strings presented to the user. */ @property (readonly, copy) NSString *localizedUppercaseString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); @property (readonly, copy) NSString *localizedLowercaseString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); @property (readonly, copy) NSString *localizedCapitalizedString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* The following methods perform localized case mappings based on the locale specified. Passing nil indicates the canonical mapping. For the user preference locale setting, specify +[NSLocale currentLocale]. */ - (NSString *)uppercaseStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); - (NSString *)lowercaseStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); - (NSString *)capitalizedStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); #pragma mark *** Finding lines, sentences, words, etc *** - (void)getLineStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)lineEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range; - (NSRange)lineRangeForRange:(NSRange)range; - (void)getParagraphStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)parEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range; - (NSRange)paragraphRangeForRange:(NSRange)range; typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) { // Pass in one of the "By" options: NSStringEnumerationByLines = 0, // Equivalent to lineRangeForRange: NSStringEnumerationByParagraphs = 1, // Equivalent to paragraphRangeForRange: NSStringEnumerationByComposedCharacterSequences = 2, // Equivalent to rangeOfComposedCharacterSequencesForRange: NSStringEnumerationByWords = 3, NSStringEnumerationBySentences = 4, // ...and combine any of the desired additional options: NSStringEnumerationReverse = 1UL << 8, NSStringEnumerationSubstringNotRequired = 1UL << 9, NSStringEnumerationLocalized = 1UL << 10 // User's default locale }; /* In the enumerate methods, the blocks will be invoked inside an autorelease pool, so any values assigned inside the block should be retained. */ - (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); - (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); #pragma mark *** Character encoding and converting to/from c-string representations *** @property (nullable, readonly) const char *UTF8String NS_RETURNS_INNER_POINTER; // Convenience to return null-terminated UTF8 representation @property (readonly) NSStringEncoding fastestEncoding; // Result in O(1) time; a rough estimate @property (readonly) NSStringEncoding smallestEncoding; // Result in O(n) time; the encoding in which the string is most compact - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy; // External representation - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding; // External representation - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding; /* Methods to convert NSString to a NULL-terminated cString using the specified encoding. Note, these are the "new" cString methods, and are not deprecated like the older cString methods which do not take encoding arguments. Also, cString methods should be used just with 8-bit encodings, and not encodings such as UTF-16 or UTF-32. For those, use methods such as getCharacters:range: (for UTF-16 characters in system endianness) or getBytes:... (which can take any encoding). */ - (nullable const char *)cStringUsingEncoding:(NSStringEncoding)encoding NS_RETURNS_INNER_POINTER; // "Autoreleased"; NULL return if encoding conversion not possible; for performance reasons, lifetime of this should not be considered longer than the lifetime of the receiving string (if the receiver string is freed, this might go invalid then, before the end of the autorelease scope). Use only with 8-bit encodings, and not encodings such as UTF-16 or UTF-32. - (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding; // NO return if conversion not possible due to encoding errors or too small of a buffer. The buffer should include room for maxBufferCount bytes; this number should accomodate the expected size of the return value plus the NULL termination character, which this method adds. (So note that the maxLength passed to this method is one more than the one you would have passed to the deprecated getCString:maxLength:.) Use only with 8-bit encodings, and not encodings such as UTF-16 or UTF-32. /* Use this to convert string section at a time into a fixed-size buffer, without any allocations. Does not NULL-terminate. buffer is the buffer to write to; if NULL, this method can be used to computed size of needed buffer. maxBufferCount is the length of the buffer in bytes. It's a good idea to make sure this is at least enough to hold one character's worth of conversion. usedBufferCount is the length of the buffer used up by the current conversion. Can be NULL. encoding is the encoding to convert to. options specifies the options to apply. range is the range to convert. leftOver is the remaining range. Can be NULL. YES return indicates some characters were converted. Conversion might usually stop when the buffer fills, but it might also stop when the conversion isn't possible due to the chosen encoding. */ - (BOOL)getBytes:(nullable void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(nullable NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(nullable NSRangePointer)leftover; /* These return the maximum and exact number of bytes needed to store the receiver in the specified encoding in non-external representation. The first one is O(1), while the second one is O(n). These do not include space for a terminating null. */ - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(1) time; the estimate may be way over what's needed. Returns 0 on error (overflow) - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(n) time; the result is exact. Returns 0 on error (cannot convert to specified encoding, or overflow) @property (class, readonly) const NSStringEncoding *availableStringEncodings; + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding; /* User-dependent encoding whose value is derived from user's default language and potentially other factors. The use of this encoding might sometimes be needed when interpreting user documents with unknown encodings, in the absence of other hints. This encoding should be used rarely, if at all. Note that some potential values here might result in unexpected encoding conversions of even fairly straightforward NSString content --- for instance, punctuation characters with a bidirectional encoding. */ @property (class, readonly) NSStringEncoding defaultCStringEncoding; // Should be rarely used #pragma mark *** Other *** @property (readonly, copy) NSString *decomposedStringWithCanonicalMapping; @property (readonly, copy) NSString *precomposedStringWithCanonicalMapping; @property (readonly, copy) NSString *decomposedStringWithCompatibilityMapping; @property (readonly, copy) NSString *precomposedStringWithCompatibilityMapping; - (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator; - (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set; - (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex; /* Returns a string with the character folding options applied. theOptions is a mask of compare flags with *InsensitiveSearch suffix. */ - (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); /* Replace all occurrences of the target string in the specified range with replacement. Specified compare options are used for matching target. If NSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch. */ - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); /* Replace all occurrences of the target string with replacement. Invokes the above method with 0 options and range of the whole string. */ - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); /* Replace characters in range with the specified string, returning new string. */ - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); typedef NSString *NSStringTransform NS_EXTENSIBLE_STRING_ENUM; /* Perform string transliteration. The transformation represented by transform is applied to the receiver. reverse indicates that the inverse transform should be used instead, if it exists. Attempting to use an invalid transform identifier or reverse an irreversible transform will return nil; otherwise the transformed string value is returned (even if no characters are actually transformed). You can pass one of the predefined transforms below (NSStringTransformLatinToKatakana, etc), or any valid ICU transform ID as defined in the ICU User Guide. Arbitrary ICU transform rules are not supported. */ - (nullable NSString *)stringByApplyingTransform:(NSStringTransform)transform reverse:(BOOL)reverse API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); // Returns nil if reverse not applicable or transform is invalid FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToKatakana API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToHiragana API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToHangul API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToArabic API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToHebrew API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToThai API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToCyrillic API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformLatinToGreek API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformToLatin API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformMandarinToLatin API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformHiraganaToKatakana API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformFullwidthToHalfwidth API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformToXMLHex API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformToUnicodeName API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformStripCombiningMarks API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT NSStringTransform const NSStringTransformStripDiacritics API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* Write to specified url or path using the specified encoding. The optional error return is to indicate file system or encoding errors. */ - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error; - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error; @property (readonly, copy) NSString *description; @property (readonly) NSUInteger hash; #pragma mark *** Initializers *** /* In general creation methods in NSString do not apply to subclassers, as subclassers are assumed to provide their own init methods which create the string in the way the subclass wishes. Designated initializers of NSString are thus init and initWithCoder:. */ - (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */ - (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length; - (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString; - (instancetype)initWithString:(NSString *)aString; - (instancetype)initWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); - (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0); - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale, ... NS_FORMAT_FUNCTION(1,3); - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0); - (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding; - (nullable instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding; - (nullable instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */ + (instancetype)string; + (instancetype)stringWithString:(NSString *)string; + (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length; + (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString; + (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + (instancetype)localizedStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); - (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding; + (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc; /* These use the specified encoding. If nil is returned, the optional error return indicates problem that was encountered (for instance, file system or encoding errors). */ - (nullable instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; - (nullable instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; /* These try to determine the encoding, and return the encoding which was used. Note that these methods might get "smarter" in subsequent releases of the system, and use additional techniques for recognizing encodings. If nil is returned, the optional error return indicates problem that was encountered (for instance, file system or encoding errors). */ - (nullable instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; - (nullable instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; @end typedef NSString * NSStringEncodingDetectionOptionsKey NS_STRING_ENUM; @interface NSString (NSStringEncodingDetection) #pragma mark *** Encoding detection *** /* This API is used to detect the string encoding of a given raw data. It can also do lossy string conversion. It converts the data to a string in the detected string encoding. The data object contains the raw bytes, and the option dictionary contains the hints and parameters for the analysis. The opts dictionary can be nil. If the string parameter is not NULL, the string created by the detected string encoding is returned. The lossy substitution string is emitted in the output string for characters that could not be converted when lossy conversion is enabled. The usedLossyConversion indicates if there is any lossy conversion in the resulted string. If no encoding can be detected, 0 is returned. The possible items for the dictionary are: 1) an array of suggested string encodings (without specifying the 3rd option in this list, all string encodings are considered but the ones in the array will have a higher preference; moreover, the order of the encodings in the array is important: the first encoding has a higher preference than the second one in the array) 2) an array of string encodings not to use (the string encodings in this list will not be considered at all) 3) a boolean option indicating whether only the suggested string encodings are considered 4) a boolean option indicating whether lossy is allowed 5) an option that gives a specific string to substitude for mystery bytes 6) the current user's language 7) a boolean option indicating whether the data is generated by Windows If the values in the dictionary have wrong types (for example, the value of NSStringEncodingDetectionSuggestedEncodingsKey is not an array), an exception is thrown. If the values in the dictionary are unknown (for example, the value in the array of suggested string encodings is not a valid encoding), the values will be ignored. */ + (NSStringEncoding)stringEncodingForData:(NSData *)data encodingOptions:(nullable NSDictionary<NSStringEncodingDetectionOptionsKey, id> *)opts convertedString:(NSString * _Nullable * _Nullable)string usedLossyConversion:(nullable BOOL *)usedLossyConversion API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); /* The following keys are for the option dictionary for the string encoding detection API. */ FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionSuggestedEncodingsKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSArray of NSNumbers which contain NSStringEncoding values; if this key is not present in the dictionary, all encodings are weighted the same FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionDisallowedEncodingsKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSArray of NSNumbers which contain NSStringEncoding values; if this key is not present in the dictionary, all encodings are considered FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionUseOnlySuggestedEncodingsKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSNumber boolean value; if this key is not present in the dictionary, the default value is NO FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionAllowLossyKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSNumber boolean value; if this key is not present in the dictionary, the default value is YES FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionFromWindowsKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSNumber boolean value; if this key is not present in the dictionary, the default value is NO FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionLossySubstitutionKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSString value; if this key is not present in the dictionary, the default value is U+FFFD FOUNDATION_EXPORT NSStringEncodingDetectionOptionsKey const NSStringEncodingDetectionLikelyLanguageKey API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // NSString value; ISO language code; if this key is not present in the dictionary, no such information is considered @end @interface NSString (NSItemProvider) <NSItemProviderReading, NSItemProviderWriting> @end @interface NSMutableString : NSString #pragma mark *** Mutable string *** /* NSMutableString primitive (funnel) method. See below for the other mutation methods. */ - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString; @end @interface NSMutableString (NSMutableStringExtensionMethods) /* Additional mutation methods. For subclassers these are all available implemented in terms of the primitive replaceCharactersInRange:range: method. */ - (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc; - (void)deleteCharactersInRange:(NSRange)range; - (void)appendString:(NSString *)aString; - (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); - (void)setString:(NSString *)aString; /* This method replaces all occurrences of the target string with the replacement string, in the specified range of the receiver string, and returns the number of replacements. NSBackwardsSearch means the search is done from the end of the range (the results could be different); NSAnchoredSearch means only anchored (but potentially multiple) instances will be replaced. NSLiteralSearch and NSCaseInsensitiveSearch also apply. NSNumericSearch is ignored. Use NSMakeRange(0, [receiver length]) to process whole string. If NSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch. */ - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange; /* Perform string transliteration. The transformation represented by transform is applied to the given range of string in place. Only the specified range will be modified, but the transform may look at portions of the string outside that range for context. If supplied, resultingRange is modified to reflect the new range corresponding to the original range. reverse indicates that the inverse transform should be used instead, if it exists. Attempting to use an invalid transform identifier or reverse an irreversible transform will return NO; otherwise YES is returned, even if no characters are actually transformed. You can pass one of the predefined transforms listed above (NSStringTransformLatinToKatakana, etc), or any valid ICU transform ID as defined in the ICU User Guide. Arbitrary ICU transform rules are not supported. */ - (BOOL)applyTransform:(NSStringTransform)transform reverse:(BOOL)reverse range:(NSRange)range updatedRange:(nullable NSRangePointer)resultingRange API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* In addition to these two, NSMutableString responds properly to all NSString creation methods. */ - (NSMutableString *)initWithCapacity:(NSUInteger)capacity; + (NSMutableString *)stringWithCapacity:(NSUInteger)capacity; @end FOUNDATION_EXPORT NSExceptionName const NSCharacterConversionException; FOUNDATION_EXPORT NSExceptionName const NSParseErrorException; // raised by -propertyList #define NSMaximumStringLength (INT_MAX-1) #pragma mark *** Deprecated/discouraged APIs *** @interface NSString (NSExtendedStringPropertyListParsing) /* These methods are no longer recommended since they do not work with property lists and strings files in binary plist format. Please use the APIs in NSPropertyList.h instead. */ - (id)propertyList; - (nullable NSDictionary *)propertyListFromStringsFileFormat; @end @interface NSString (NSStringDeprecated) /* The following methods are deprecated and will be removed from this header file in the near future. These methods use NSString.defaultCStringEncoding as the encoding to convert to, which means the results depend on the user's language and potentially other settings. This might be appropriate in some cases, but often these methods are misused, resulting in issues when running in languages other then English. UTF8String in general is a much better choice when converting arbitrary NSStrings into 8-bit representations. Additional potential replacement methods are being introduced in NSString as appropriate. */ - (nullable const char *)cString NS_RETURNS_INNER_POINTER API_DEPRECATED("Use -cStringUsingEncoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable const char *)lossyCString NS_RETURNS_INNER_POINTER API_DEPRECATED("Use -cStringUsingEncoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (NSUInteger)cStringLength API_DEPRECATED("Use -lengthOfBytesUsingEncoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (void)getCString:(char *)bytes API_DEPRECATED("Use -getCString:maxLength:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength API_DEPRECATED("Use -getCString:maxLength:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength range:(NSRange)aRange remainingRange:(nullable NSRangePointer)leftoverRange API_DEPRECATED("Use -getCString:maxLength:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile API_DEPRECATED("Use -writeToFile:atomically:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically API_DEPRECATED("Use -writeToURL:atomically:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable id)initWithContentsOfFile:(NSString *)path API_DEPRECATED("Use -initWithContentsOfFile:encoding:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable id)initWithContentsOfURL:(NSURL *)url API_DEPRECATED("Use -initWithContentsOfURL:encoding:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); + (nullable id)stringWithContentsOfFile:(NSString *)path API_DEPRECATED("Use +stringWithContentsOfFile:encoding:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); + (nullable id)stringWithContentsOfURL:(NSURL *)url API_DEPRECATED("Use +stringWithContentsOfURL:encoding:error: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable id)initWithCStringNoCopy:(char *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer API_DEPRECATED("Use -initWithCString:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable id)initWithCString:(const char *)bytes length:(NSUInteger)length API_DEPRECATED("Use -initWithCString:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); - (nullable id)initWithCString:(const char *)bytes API_DEPRECATED("Use -initWithCString:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); + (nullable id)stringWithCString:(const char *)bytes length:(NSUInteger)length API_DEPRECATED("Use +stringWithCString:encoding:", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); + (nullable id)stringWithCString:(const char *)bytes API_DEPRECATED("Use +stringWithCString:encoding: instead", macos(10.0,10.4), ios(2.0,2.0), watchos(2.0,2.0), tvos(9.0,9.0)); /* This method is unsafe because it could potentially cause buffer overruns. You should use -getCharacters:range: instead. */ - (void)getCharacters:(unichar *)buffer; @end NS_ENUM(NSStringEncoding) { NSProprietaryStringEncoding = 65536 /* Installation-specific encoding */ }; /* The rest of this file is bookkeeping stuff that has to be here. Don't use this stuff, don't refer to it. */ #if !defined(_OBJC_UNICHAR_H_) #define _OBJC_UNICHAR_H_ #endif #define NS_UNICHAR_IS_EIGHT_BIT 0 @interface NSSimpleCString : NSString { @package char *bytes; int numBytes; #if __LP64__ int _unused; #endif } @end @interface NSConstantString : NSSimpleCString @end #if __LP64__ #else extern void *_NSConstantStringClassReference; #endif NS_ASSUME_NONNULL_END