OC learning --- NSString object and NSMutableString object in the Foundation framework, nsmutablestring

Source: Internet
Author: User

OC learning --- NSString object and NSMutableString object in the Foundation framework, nsmutablestring

In the previous article, we mentioned the NSObject object in the Foundation framework:

Http://blog.csdn.net/jiangwei0910410003/article/details/41788121

Now, let's take a look at the common objects in the Foundation framework: NSString and NSMutableString.

In OC, NSString objects are immutable, which is the same as String in Java, while NSMutableString is variable, which is the same as StringBuilder in Java.


1. NSString object

In OC, The NSString object is a very important object and the most basic object. It is a common class used to process strings. It is very similar to the String class in Java, and some of his methods are similar.

Let's take a look at the use of some NSString methods:

//// Main. m // 14_NSString /// Created by jiangwei on 14-10-11. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> int main (int argc, const char * argv []) {@ autoreleasepool {// NSString is an immutable string and will be downgraded to a variable string // 1. -------------- string creation method NSString * string1 = @ "hello"; NSLog (@ "% @", string1 ); // The method above is equivalent to string1 = [[NSString alloc] initWithString: @ "hello1"]; NSLog (@ "% @", s Tring1); // placeholder, which can be concatenated into strings // [string1 stringByAppendingFormat: <# (NSString *),... #>] This method can also be used to concatenate strings in string1 = [[NSString alloc] initWithFormat: @ "hello % @", string1]; NSLog (@ "% @", string1); // use the class method to create a string string1 = [NSString stringWithString: @ "hello1"]; // 2. -------------- comparison of string values of the isEqualToString // NSString * string2 = @ "abcd"; NSString * string3 = @ "8888"; BOOL isEquals = [string2 isEqualToString: str Ing3]; if (isEquals) {} else {} NSString * string8 = @ "abc"; NSString * string9 = @ "abc"; // The memory is optimized here, here, string8 and string9 are the same. The "abc" allocated in the constant area // string8 and string9 are local variables, and the if (string8 = string9) memory allocated in the stack) {NSLog (@ "string8 = string9");} else {NSLog (@ "string8! = String9 ");} // The string11 and string12 below are still the NSString * string11 = [[NSString alloc] initWithString: @" abc "] allocated memory in the stack. NSString * string12 = [[NSString alloc] initWithString: @ "abc"]; if (string11 = string12) {NSLog (@ "string11 = string12 ");} else {NSLog (@ "string11! = String12 ");} // The string13 and string14 below are allocated memory in the heap, so string13 and string14 are not equal to NSString * string13 = [[NSString alloc] initWithFormat: @ "abc % @", @ "def"]; NSString * string14 = [[NSString alloc] initWithFormat: @ "abc % @", @ "def"]; if (string13 = string14) {NSLog (@ "string13 = string14");} else {NSLog (@ "string13! = String14 ");} // 3. use Case Insensitive to determine whether the values are equal NSString * string15 = @ "zhangsan"; NSString * string16 = @ "ZAHNGSAN"; NSComparisonResult result = [string15 caseInsensitiveCompare: string16]; if (result = NSOrderedSame) {} else {} // 4. --------------------- compare method // compare the size of two strings result = [string15 compare: string16]; if (result = NSOrderedAscending) {// ascending} else if (result = NSOrderedDescending) {// descending} // 5. --------------------- length method NSString * string17 = @ "abc"; NSInteger len = [string17 length]; NSLog (@ "len = % ld", len); // 6. --------------------- uppercaseString/lowercaseString // convert it to an upper-case NSString * string18 = @ "aEc"; NSString * string19 = [string18 uppercaseString]; string19 = [string18 lowercaseString];/uppercase, other values are changed to lower case [string18 capitalizedString]; // 7. ------------------ --- TypeXXXValue // numeric conversion method NSString * string20 = @ "3.14"; float value = [string20 floatValue]; string20 = @ "1"; BOOL values = [string20 boolValue]; // 8. --------------------- subStringToIndex/subStringFromIndex/subStringWithRange // capture NSString * string21 = @ "abcdefg"; // extract a string from the starting position to the string with the subscript 3 (excluding 3) NSString * stringnews = [string21 substringToIndex: 3]; // The index from which it is intercepted to the end (including 3) stringnews = [string21 substring FromIndex: 3]; // intercept 1 ~ (3 + 1) The part of the string nsange range = {1, 3}; stringnews = [string21 substringWithRange: range]; // 9. append NSString * string22 = @ "Android"; NSString * stringnew = [string22 stringByAppendingString: @ "IOS"]; stringnew = [string22 string22 stringByAppendingFormat: @ "% @", @ "IOS"]; // 10. --------------------- rangeOfString // search NSString * string23 = @ "www.iphonetrain.com/ios.html"; nsange rang = [string23 rangeOfString: @ "ios"]; // return a range if (rang. location = NSNotFound) {// not found} else {// found} // 11. ---------------------- characterAtIndex // retrieve the specified char NSString * string24 = @ "abcdef"; unichar c = [string24 characterAtIndex: 3];} return 0 ;}


Let's take a look at his method:

1. Creation Method

// 1. -------------- string creation method NSString * string1 = @ "hello"; NSLog (@ "% @", string1 ); // It is equivalent to string1 = [[NSString alloc] initWithString: @ "hello1"]; NSLog (@ "% @", string1); // placeholder, concatenation string // [string1 stringByAppendingFormat: <# (NSString *),... #>] This method can also be used to concatenate strings in string1 = [[NSString alloc] initWithFormat: @ "hello % @", string1]; NSLog (@ "% @", string1); // use the class method to create a string string1 = [NSString stringWithString: @ "hello1"];
Here we use four methods to create a string

We usually use the first method.

The second is the object method created

The third method is to concatenate strings when creating strings.

The fourth type is created using the class method.


2. Compare the string value

// 2. -------------- comparison of string values of isdomaintostring // NSString * string2 = @ "abcd"; NSString * string3 = @ "8888"; BOOL isEquals = [string2 isdomaintostring: string3]; if (isEquals) {} else {}
This method is simple and there is nothing to say

However, this method must be different from the = method we mentioned before to determine the equal mode. The = method is the same as the isEqual method. It compares whether the pointer variable points to the same object, but there is a special character string in OC. Let's take a look at the code below:

NSString * string8 = @ "abc"; NSString * string9 = @ "abc"; // The memory is optimized. Here, string8 and string9 are the same, "abc" in the constant area, the allocated // string8 and string9 are local variables, and the if (string8 = string9) of the memory allocated in the stack) {NSLog (@ "string8 = string9");} else {NSLog (@ "string8! = String9 ");}
After running, we can find that the = clause is equal. This is similar to the situation in Java. in Java, there is a constant pool concept, such as a string created in this way, their values are stored in a constant pool, and then the reference is the object pointing to the constant pool, so the = is equal, and the reason in OC is similar.

But let's look at the following code:

// The string11 and string12 below are the NSString * string11 = [[NSString alloc] initWithString: @ "abc"] allocated memory in the stack. NSString * string12 = [[NSString alloc] initWithString: @ "abc"]; if (string11 = string12) {NSLog (@ "string11 = string12 ");} else {NSLog (@ "string11! = String12 ");}
We found that the string created using the initWithString initialization method also points to the same object, so remember here, the string created by the initWithString method in the NSString class is the same as that created by the NSString * str = @ "demo" method. It all points to an object in the constant pool. Therefore, the = method is equivalent. The method used to create a string in other NSString classes is different. For example, the following code:

// The following string13 and string14 are allocated memory in the heap, so string13 and string14 are not equal to NSString * string13 = [[NSString alloc] initWithFormat: @ "abc % @", @ "def"]; NSString * string14 = [[NSString alloc] initWithFormat: @ "abc % @", @ "def"]; if (string13 = string14) {NSLog (@ "string13 = string14");} else {NSLog (@ "string13! = String14 ");}
The object created using the initWithFormat initialization method does not need to wait.

Remember that the initWithString initialization method works the same as creating a string directly. It all points to the NSString object in the constant pool.


3. Compare the size of two strings

// 4. --------------------- compare method // compare the size of two strings result = [string15 compare: string16]; if (result = NSOrderedAscending) {// ascending} else if (result = NSOrderedDescending) {// descending order}

4. String Length Method

// 5. --------------------- length method NSString * string17 = @ "abc"; NSInteger len = [string17 length]; NSLog (@ "len = % ld", len );


5. Convert string case
// 6. --------------------- uppercaseString/lowercaseString // convert it to an upper-case NSString * string18 = @ "aEc"; NSString * string19 = [string18 uppercaseString]; string19 = [string18 lowercaseString];/uppercase, other values are changed to lower case [string18 capitalizedString];

6. Numerical Conversion Method

// 7. ------------------- TypeXXXValue // numeric conversion method NSString * string20 = @ "3.14"; float value = [string20 floatValue]; string20 = @ "1"; BOOL values = [string20 boolValue];


7. String truncation method

// 8. --------------------- subStringToIndex/subStringFromIndex/subStringWithRange // capture NSString * string21 = @ "abcdefg"; // extract a string from the starting position to the string with the subscript 3 (excluding 3) NSString * stringnews = [string21 substringToIndex: 3]; // The index from which it is intercepted to the end (including 3) stringnews = [string21 substringFromIndex: 3]; // intercept 1 ~ (3 + 1) The part of the string nsange range = {1, 3}; stringnews = [string21 substringWithRange: range];

8. String appending Method

// 9. append NSString * string22 = @ "Android"; NSString * stringnew = [string22 stringByAppendingString: @ "IOS"]; stringnew = [string22 string22 stringByAppendingFormat: @ "% @", @ "IOS"];

Note that a new string is returned after each append of a string, because NSString is an immutable class. Similar to the String class in Java, if you use + to connect strings, A New String object will be created. In Java, you can use the StringBuilder object to solve this problem, there is also a solution in OC, and a variable string class will be mentioned later


9. String Search Method

// 10. --------------------- rangeOfString // search NSString * string23 = @ "www.iphonetrain.com/ios.html"; nsange rang = [string23 rangeOfString: @ "ios"]; // return a range if (rang. location = NSNotFound) {// not found} else {// found}


11. Retrieve the specified char in the string

// 11. -------------------- characterAtIndex // retrieve the specified charNSString * string24 = @ "abcdef"; unichar c = [string24 characterAtIndex: 3];


Ii. NSMutableString object

Some common methods of NSString objects are introduced above, but NSString in OC is an immutable object. So here we will introduce a variable object corresponding to it:

NSMutableString

Take a look at the Code:

//// Main. m // 15_NSMutableString /// Created by jiangwei on 14-10-12. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> // The content in NSMutableString can be modified. // NSMutableString inherits the int main (int argc, const char * argv []) of the NSString class. {@ autoreleasepool {// 1. -------------------- create a string // the same method as NSString. NSMutableString * string1 = [[NSMutableString alloc] initWithString: @ "hello"]; // but cannot be created using the following method // because the string created in the following method is immutable, its value is placed in the constant pool, it cannot be // NSMutableString * string1 = @ "hello"; // 2. --------------------- insertString // insert a string in the index specified in the source string, and no new object [string1 insertString: @ "variable" atIndex: 0] will be generated; // 3. --------------------- appendString // append the string. No new object [string1 appendString: @ "variable"] is generated. // 4. --------------------- deleteCharactersInRange // Delete the string content of the specified range in the string. NSMutableString * string2 = [NSMutableString stringWithString: @ "hello"]; nsutrange = {1, 3}; [string2 deleteCharactersInRange // 5. ------------------- replaceCharactersInRange // replace string content NSMutableString * string3 = [NSMutableString stringWithString: @ "hello"]; nsange ranges = [string3 rangeOfString: @ "ll"]; // first query and find out the value range of the string to be replaced [string3 replaceCharactersInRange: ranges withString: @ "ee"];} return 0 ;}
This section describes the differences between the NSMutalbeString class and the NSString class.


1. Creation Method

The NSMutableString class can be created in the same way as NSString, but note that NSMutableString cannot be created directly because the directly created strings are in the constant pool, the values in the constant pool are unchangeable, so they cannot be created. Meanwhile, the strings created by initWithString are not in the constant pool. This must be distinguished from NSString.


2. Insert a string

// 2. --------------------- insertString // insert a string in the index specified in the source string without generating a new object [string1 insertString: @ "variable" atIndex: 0];

3. append a string

// 3. --------------------- appendString // append the string without generating a new object [string1 appendString: @ "variable"];
This append method is different from NSString and does not generate a String object.


4. delete a string

// 4. --------------------- deleteCharactersInRange // Delete the string content of the specified range in the string. NSMutableString * string2 = [NSMutableString stringWithString: @ "hello"]; nsutrange = {1, 3}; [string2 deleteCharactersInRange

5. Replace strings
// 5. ------------------- replaceCharactersInRange // replace string content NSMutableString * string3 = [NSMutableString stringWithString: @ "hello"]; nsange ranges = [string3 rangeOfString: @ "ll"]; // first check the range of the string to be replaced [string3 replaceCharactersInRange: ranges withString: @ "ee"];


From the above methods, we can also see that the NSMutableString class is variable, because only variable strings are added, deleted, modified, and queried.


Summary

This article introduces the string objects in the Foundation framework, including variable NSMutableString and unchanged NSString.












Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.