NSString
OC provides a way to define a string object, which is to enclose the string you want to express in a pair of double quotation marks, and at the beginning plus @[email protected] is the instruction in OC, which tells the compiler that the content after @ is the syntax in OC. For example @ "Harbingwang" Represents a constant of type nsstring.
NSString is an immutable string class, inherited from the NSObject, with NSString created by the string object, once created can no longer be modified. We can perform a find or compare operation on it, but not by adding, Delete its characters to change it dynamically.
NSString The main methods are defined in the Foundation/nsstring.h, NSString provides many methods of interface, but the implementation of these methods are implemented internally. The main methods of NSString are described below:
1. Quickly create a String object
NSString *str = @ "uncle about?";
2. Generate a string in the specified format
Format Create string Initwithformat:
The convenience constructor method creates stringWithFormat:
NSString *str = [[NSString alloc] initwithformat:@ "name:%@ age:%ld, name, age];
NSString *str = [NSString stringwithformat:@ "name:%@ age:%ld, name, age];
Exercise: Initialize the string @ "2015.11.18" and @ "2016.1.1" to a new string @ "2015.11.18--2016.1.1"
NSString *date = [NSString stringwithformat:@ "%@%@%@", @ "2015.11.18", @ "--", @ "2016.1.1"];
3. Convert a string in C to a string object in OC initwithutf8string:
NSString *str = [NSString alloc] initwithutf8string: "IOS"];
4. Create a String object using the text content in the file to specify the encoding format initwithcontentsoffile:<# (NSString *) #> encoding: <# (nsstringencoding) #> error:<# (nserror *__autoreleasing *) #>
First parameter: File path
Second parameter: Encoded format nsutf8stringencoding 8-bit Unicode encoding for use in Chinese encoding formats
The third parameter: if there is an error, this parameter is used to store the error message, generally fill nil
NSString *str = [[NSString alloc] initwithcontentsoffile:@ "/users/desktop/product/oc/lesson/oclessonnsstring-04/ Oclessonnsstring-04/harbingwang.txt "Encoding:nsutf8stringencoding Error:nil];
The corresponding convenience builder StringWithContentsOfFile:encoding:error:
5. Calculate the length of the string
//Whether it is a number, English or Chinese characters, is a character to calculate Nsuinteger length = string.length; //can use dot syntax NSLog (@ "%lu", length);
First add two points here:
1. The concept of a parent string and a substring: there are multiple consecutive characters in a string that are the same as the B string, a is the parent string of B, and B is a substring of a.
2. Nsrang is a structure representing the scope, which includes the first address location and data length of the data legth
typedef struct _nsrange {nsuinteger location; //Starting position/ /starting from the starting position to take how long } nsrange;
6. Interception of strings
Substringwithrange:
A. Returns a new string where the starting position and length of the new string are determined by rang
Nsrange rang = {12, 1
NSString *string = [string
Substringtoindex:
B. Getting a string starting from 0 to a location, but not including the character that provides the location
NSString *substring = [string Substringtoindex:5];
NSLog (@ "%@", substring); //Returns a new string object. So with the%@ placeholder
Substringfromindex:
C. Get a substring starting from a position to the end, containing the character that provides the location
NSString *substring = [string Substringfromindex:5
NSLog (@ "%@", substring);
7. Retrieval of strings
rangeofstring: //Returns a new string where the starting position and length of the new string are determined by rang nsstring *string = @ "ILOVEYOU";//Like a string, want the substring ' love ' in the String4 range nsrange rang1 = [string rangeofstring:@ "Love" ]; NSLog (@ "%lu%lu", Rang1.location, rang1.length);
8. Concatenation of strings
Format stitching string (can be stitched multiple)
NSString *string1 = @ "IOS"; NSString *string2 = @ "Development";
NSString *newstring = [string1 stringbyappendingformat:@ "%@", string2]; Stringbyappendingstring://splicing character channeling (only one stitching)
NSString *newstring2 = [String1 stringbyappendingstring:@ "Getting Started Basics"];//print iOS Getting Started basics
9. Substitution of strings
stringbyreplacingoccurrencesofstring:withstring: //Replace the target string from the parent string with the given string //To find the target string and return to the original string if it is not found//For example: newstring iOS Development Basics Replace iOS with androidnsstring * NewString1 = [NewString2 stringbyreplacingoccurrencesofstring:@ "IOS" withstring:@ "Android"]; Stringbyreplacingcharactersinrange:withstring:
Nsrange rang2 = {0, 2}; NSString *newstring4 = [newString3 stringbyreplacingcharactersinrange:rang2 withstring:@ "Dong"];
10. Judging
hasprefix: Determines whether a string has a prefix nsstring *str15 = @ "iOS Development Basics"; BOOL Ishas = [Str15 hasprefix:@ "IOS"];//Hasprefix returns a bool value of NSLog (@ "%@", Ishas? @ "With this prefix": @ "without this prefix"hassuffix: //Determine if a string has a suffix ishas = [Str15 hassuffix:@ "3G Academy"]; NSLog (@ "%@", Ishas @ "with this suffix": @ "without this suffix");
Isequaltostring:
//Determine if two string objects are equal
NSString *str1 = @ "IOS";
NSString *STR2 = @ "Development";
BOOL issame = [str1 isequaltostring:str2];
NSLog (@ "%@", Issame @ "Same": @ "not the same");
Practice
Determine if the string @ "Harbingwang" has a suffix of @ ". jpg", and if it does not, add a @ ". jpg" to it, and replace @ ". jpg" with @ ". png"nsstring *str = @ "Harbingwang" ;
BOOL ishasjpg = [str16 hassuffix:@ ". jpg"];
NSString *newstr = ishasjpg? [Str16 stringbyreplacingoccurrencesofstring:@ ". jpg" withstring:@ ". png"]: [str16 stringbyappendingstring:@ ". jpg" ]; NSLog (@ "%@", newstr);
11. Compare
Compare the size of two strings (case-sensitive) Compare:
Let's take a look at its declaration in the API:
-(Nscomparisonresult) Compare: (NSString *) string;//The return value is: Nscomparisonresult is a value of an enumeration type that is used to display the result of the comparison enum { nsorderedascending =-1, //Ascending, previous one less than the latter one Nsorderedsame, //Same, before and after the same nsordereddescending //Descending, previous one greater than the latter one };typedef Nsinteger nscomparisonresult;
Compare Method:
The receiving object and the passed-in string are compared by character, and a nscomparisonresult is returned to show the result of the comparison, and if Nsorderedascending is returned then the previous value is less than the next value, sorted in ascending order.For example: Compare the size of the NBA with the NBA
NSString *str18 = @ "NBA"; NSString *str19 = @ "NBA"; Nscomparisonresult n = [str18 compare:str19]; Switch (n) {
Case nsorderedascending: NSLog (@ "%@ <%@", Str18, str19); %@ = =%@ ", Str18, STR19); Nsordereddescending:nslog (@ "%@ >%@", Str18, str19); break; default: break ; } NSLog (@ "%ld", n);
//Case-insensitive comparison caseinsensitivecompare:
-(Nscomparisonresult) Caseinsensitivecompare: (NSString *) string;
Nscomparisonresult return value as above, enumeration value
Nscomparisonresult m = [Str11 caseinsensitivecompare:str12]; NSLog (@ "%ld", m); //Output 0 means Str11 and str12 are the same, case-insensitive, composite actual
Nsmutablestring
nsmutablestring A mutable string, inherited from NSString, so nsmutablestring can use all the instance variables and methods of its parent class, the string created by the class is a mutable string, can support adding and deleting changes and other dynamic operations. Generally encourage the use of the Nsmutablestring class in project development
1. Generation and initialization of instance objects initwithcapacity:
Convenient constructor method stringwithcapacity:
nsmutablestring *mstr = [[Nsmutablestring alloc] initwithcapacity:0];
nsmutablestring *mstr1 = [[nsmutablestring stringwithcapacity:0];
Initializes an object of type nsmutablestring, capacity the meaning of the capacity, indicating the size of the Nsmutablestring object to be initialized. Nsmutablestring object will automatically expand memory as the string changes, if the content is smaller than this space, it can be placed directly, if larger than the virtual space will continue to open up new space.
2. How to create a variable string quickly . Mutablecopy
Nsmutablestring *MSTR3 = @ "I am a good student". Mutablecopy; //mutablecopy A copy of the contents of a constant area to the heap area
3. Append a String
append a string to the end appendString:
appends a formatted string to the end of the AppendFormat:
nsmutablestring *mutalbestr = [nsmutablestring stringwithformat:@ "My Age is ten"appendString:// The AppendString method does not return a value, which means that it is stitched directly behind the STR string NSLog (@ "%@", mutalbestr); Print: My ageis ten//non-variable group also provides the method of stitching, we might as well contrast:nsstring *str = [NSString stringwithformat:@ "My Age is ten"
stringbyappendingstring:@ "One by one"
]; NSLog (@ "%@", str2); Print: My Age is ten
As you can see: NSString once the STR string is defined, it is inherently immutable, although the NSString class method also provides a method for stitching, such as the Stringbyappendstring method, but it returns a new string. The stitching method provided by Nsmutablestring AppendString method is to stitch it directly on the original string without the return value. This is the nature of mutable and immutable strings.
4. Method of inserting a string insertstring:atindex:
[MSTR4 insertstring:@ "blog Park" atindex:0]; NSLog (@ "%@", MSTR4);
5. Delete the substring Deletecharactersinrange according to the range :
Create a struct variable that represents a range nsrange Rang3 = Nsmakerange (0, 2);//delete substring by range Deletecharactersinrange:[(Parent string) DELETECHARACTERSINRANGE:RANG3]; NSLog (@ "%@", mStr2);
6. Assign a value to the string object, copy the astring, and set it to the content of the message recipient setString
7. About capitalization
uppercasestring//capitalizes each character of the string mStr3 nsstring *upstring = [MSTR3 uppercasestring];//can call the method directly, You can also use dot syntax nsstring *upstring = mstr3.uppercasestring; 8 Each character of the string is all lowercase lowercasestringnsstring *lowstring = mstr3.lowercasestring; 9capitalizedstring
NSString *capitonstring = mstr3.capitalizedstring;
Objective-c Study 06-nsstring and nsmutablstring