OC section II--nsstring and Nsmutablestring

Source: Internet
Author: User

1. Why do I need nsstring objects
A: When you create a string in OC, you generally do not use the C method.
Because C takes a string as an array of characters, there are many inconvenient things to do in the operation.
Some methods of nsstring integration in cocoa can easily manipulate strings,


Comparison of strings and C strings in 2.oc
"Hello World"
@ "Hello World"


1) Output Mode%@
2) Citation method
NSString begins with the @ sign, indicating that the string is a string of OC type
C language string does not start with @

Conversion of 3.c language strings and NSString
1) stringwithcstring:encoding: Message
Function: Converts a C string to an OC string object by the specified encoding
NSString *STR2 = [nsstring STRINGWITHCSTRING:CSTR encoding:
Nsutf8stringencoding];

2) utf8string Message
Function: Converts a NSString object to a C string by UTF8 encoding
And the result of the conversion is a const char * type string
const char *CSTR2 = [str2 utf8string];

Output mode: You can use printf to output

3) What is character encoding
is a set of rules that can be used to pair a set of natural language characters (such as an alphabet or a syllable table) with a set of other things (such as a number or electrical pulse). That is, the corresponding relationship between the symbol set and the digital system is established.
Common character encodings: ASCII \ Gb18030\unicode

Unicode: In the field of computer science, Unicode (uniform Code, universal Code, single code, standard universal Code) is a standard in the industry, it can enable the computer to reflect the world's dozens of kinds of text system. Up to the sixth edition so far, Unicode already contains more than 100,000 characters.

Unicode is a character set, and Utf-32/utf-16/utf-8 is a three character encoding scheme.
UTF-32: Use 4-byte numbers to express each letter, symbol, or ideographs (Ideograph)
UTF-16: Each character only needs 2 bytes to store, if beyond the 0~65535, then take the bizarre technique to implement.
UTF-8: UTF-8 is a variable-length encoding for Unicode that encodes each character with one to four bytes. It is gradually becoming the preferred encoding for e-mail, Web pages, and other applications that store or transmit text. The Internet Engineering Task Force (IETF) requires that all Internet protocols must support UTF-8 encoding.


How 4.NSString is created
NSString *str [email protected] "ios"; Creating Immutable strings

Instantiating a method to create a string
Initializes an OC string object with an OC constant string
-(Instancetype) initwithstring: (NSString *) astring;
-(Instancetype) Initwithformat: (nsstring*) format,...;
-(Instancetype) initwithutf8string: (const char *) bytes;

class method to create a string
+ (Instancetype) stringwithstring: (nsstring*) astring;
+ (Instancetype) stringWithFormat: (NSString *) format,...;
+ (Instancetype) stringwithutf8string: (const char *) bytes;

Common methods of NSString:

1. Find the length of the string
-(nsuinteger) length;

2. Get the corresponding characters by index
-(Unichar) Characteratindex: (Nsuinteger) index;

3. Comparison of strings
3.1 Comparison of two strings for equality
Isequaltostring: Message
Recall: How to compare two strings for equality in C language
-(BOOL) isequaltostring: (NSString *) astring;

Compare: Message
3.2 Comparing the size of two strings
-(Nscomparisonresult) Compare: (NSString *) astring;

3.3 Comparison with case insensitive
Compare:option
-(Nscomparisonresult) Compare: (NSString *) astring options:
Nscaseinsensitivesearch;

Caseinsensitivecompare: Message
-(Nscomparisonresult) Caseinsensitivecompare: (NSString *) astring;




4. String Lookup

1) rangeofstring Message
-(Nsrange) rangeofstring: (NSString *) astring;

Function: Finds whether the specified string is in the target string and returns Nsrange
Structural body.
Location
Length

If present, the returned Nsrange will contain the starting position and the length
If not present, nsrange.location = = Nsnotfound

Exercise: 1. Find the location of the "fine" string in "Hi, I am Fine,and You"


5. Judging the prefix
-(BOOL) Hasprefix: (NSString *) astring;
-(BOOL) Hassuffix: (NSString *) astring;

6. Digital string conversion to Digital
-(double) doublevalue;
-(float) floatvalue;
-(int) intvalue;
-(Nsinteger) IntegerValue;
-(long long) longlongvalue;

7. Capitalization conversion
-(NSString *) uppercasestring;
-(NSString *) lowercasestring;

8. String extraction

1) Substringfromindex Message
Function: Extracts the string from the specified position, returns the string address, and closes the interval

2) Substringtoindex Message
Function: Extracts the string from the beginning to the specified position, returns the string address, opens the interval

#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {nsstr                ing *ocstr = @ "IOS"; 1.        The length of the string is Nsuinteger len = [ocstr length];   NSLog (@ "len =%lu", Len); 3//2. Get characters by index//ocstr[0];        OC string can not use subscript unichar C = [Ocstr characteratindex:0];                        Unichar Format Translator%c NSLog (@ "c =%c", c);        3. String comparison nsstring *ocstr1 = @ "Hello";                NSString *ocstr2 = @ "HellO";        ------Compare whether two strings are equal-------//isequaltostring:bool ret = [ocStr1 ISEQUALTOSTRING:OCSTR2];        if (ret = = YES) {NSLog (@ "OCSTR1 = = OcStr2");        } else {NSLog (@ "OCSTR1! = ocStr2"); }/* typedef enum {nsorderedascending = -1l, nsorderedsame                     = 0, nsordereddescending = 1}nscomparisonresult;     RET is an enumeration variable    Nscomparisonresult ret;  int A;  Define variable typedef int INT_32;                  A new alias is given to the INT type int_32 typedef long INT_64;                  Use INT_32 to declare variables int_32 B, C, D;            struct Stuinfo {char *name;         int age;         };         typedef struct STUINFO Stu;                           Stu Stu; typedef: The function is to give the type alias *///-------Compare the size of the string----------Nscompa        Risonresult Ret1 = [OcStr1 compare:ocstr2];                Switch (RET1) {case nsorderedascending://-1l NSLog (@ "OcStr1 < OCSTR2");            Break                Case nsordereddescending://1l NSLog (@ "OCSTR1 > ocStr2");            Break            Case Nsorderedsame:nslog (@ "OCSTR1 = = OcStr2");        Default:break; }//-------Ignore character case comparisons-----------nscomparisonresult ret2 = [OCSTR1 CompARE:OCSTR2 Options:nscaseinsensitivesearch];        if (Ret2 = = nsorderedascending) {NSLog (@ "OcStr1 < OCSTR2");        } else if (Ret2 = = nsordereddescending) {NSLog (@ "OCSTR1 > ocStr2");        } else {NSLog (@ "OCSTR1 = = OcStr2");        //4. String lookup NSString *ocstr3 = @ "When I am young, I was a student";                NSString *OCSTR4 = @ "was";   /* typedef struct _NSRANGE {Nsuinteger location;     Subscript Nsuinteger Length;         length} Nsrange; *///rangeofstring: (NSString *) astring//forward lookup, returns the structure of the information for the first occurrence of the string//if present, returns the starting position in the long string and the length of the match (the short pass has        Effect length)//If the lookup fails: return starting position nsnotfound Nsrange range;        Range = [OcStr3 RANGEOFSTRING:OCSTR4];        if (range.location! = nsnotfound) {NSLog (@ "Location:%lu, Length:%lu", Range.location, Range.length);            } else {NSLog (@ "not found!"); NSLog (@ "Nsnotfound =%lx ", nsnotfound); Signed number 01111111111: 11111}//Search from the back nsbackwardssearch range = [OcStr3 rangeofstring:ocstr4 OPTIONS:NSBACKWARDSS        Earch]; if (range.location = = Nsnotfound) {NSLog (@ "not found!");}        else {NSLog (@ "Location:%lu, Length:%lu", Range.location, Range.length);        }//_______________ string Find practice ________________________ char *cstr = "Hi, I am Fine,and you";        NSString *ocstring = [NSString stringwithutf8string:cstr];        Nsrange Range1 = [ocstring rangeofstring:@ "Fine"];        if (range1.location = = Nsnotfound) {NSLog (@ "not found");        } else {NSLog (@ "Location:%lu, Lenght:%lu", Range1.location, Range1.length); }//5.                Determine the prefix and suffix of the string//hasprefix//hassuffix nsstring *site = @ "http://www.baidu.com";        Determine if site is starting with http BOOL ret3 = [site hasprefix:@ "http"]; NSLog (@ "reT3 =%d ", ret3);        NSString *mp3str = @ "The most famous Clan wind. mp3";        Ret3 = [mp3str hassuffix:@ "MP3"];                                NSLog (@ "Ret3 =%d", ret3); 6.        The numeric string Object--------------> Simple number//@ "12345"---> 12345 nsstring *intstr = @ "12345";        int num = [Intstr intvalue];                NSLog (@ "num =%d", num);        NSString *floatstr = @ "3.14";        float f = [floatstr floatvalue];                NSLog (@ "f =%f", f);        Nsinteger inter = [Intstr integervalue];                        NSLog (@ "inter =%ld", inter); 7.        Uppercase and lowercase conversions nsstring *lowerstr = @ "Zhangsan";        NSString *upperstr = [Lowerstr uppercasestring];                NSLog (@ "upperstr =%@", upperstr);        NSString *lowerstr1 = [Upperstr lowercasestring];                     NSLog (@ "LOWERSTR1 =%@", lowerStr1); NSString *str1 = [Lowerstr capitalizedstring];                        Converts the initial letter to the size letter NSLog (@ "str1 =%@", str1); 8. Extracting strings, extracting sub-strings NSString *string1 = @ "When I am a young, I like a girl on my Neibour class";        Starting from one subscript to the end [] closed interval nsstring *SUBSTR1 = [string1 substringfromindex:5];                NSLog (@ "SUBSTR1 =%@", subStr1);        From the beginning of the first letter is extracted to a character in front of the parameter, [) open interval nsstring *substr2 = [string1 substringtoindex:4];                NSLog (@ "SUBSTR2 =%@", SUBSTR2);        Extracts substrings according to a range nsrange Range2 = {1, 4};        NSString *SUBSTR3 = [string1 substringwithrange:range2];                            NSLog (@ "SUBSTR3 =%@", SUBSTR3); } return 0;}

  Variable string common methods (all methods that contain immutable strings):

#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {//Use available                Variable pointer----> Immutable object, or immutable string//nsmutablestring *string = @ "IOS";        nsmutablestring *string = [[Nsmutablestring alloc] initwithstring:@ "Hello"];                        NSLog (@ "string =%@", string);        Variable string--(increment, delete, change)//_____________________ increase ____________________add, append//1) Append//Add (Append)        [String appendstring:@ "world"];                NSLog (@ "string =%@", string);        [String appendformat:@ "%@,%d", @ "Hi", 101];                NSLog (@ "string =%@", string);        2) Insert [string insertstring:@ "XXXXX" atindex:3];                NSLog (@ "string =%@", string); ____________________ Delete ____________________ Delete, remove [string Deletecharactersinrange:nsmakerange (3,        4)];                NSLog (@ "string =%@", string); ____________________ modified ______________________change, Replace [String Replacecharactersinrange:nsmakerange (3, 1) withstring:@ ""];                        NSLog (@ "string =%@", string);        ____________________ Reset String _______________//Set method [string setstring:@ "Laowang"];            NSLog (@ "string =%@", string); } return 0;}

OC section II--nsstring and Nsmutablestring

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.