NSString usage, object-c arrays and string concatenation and segmentation

Source: Internet
Author: User

First, Introduction
The code to create a string using NSString is as follows:


#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
Nsautoreleasepool*pool=[[nsautoreleasepool Alloc]init];


NSString *[email protected] "programming is fun";
NSLog (@ "%@", str);


[Pool drain];
return 0;
}
Objective-c strings are made up of char, nsstring strings are composed of Unichar, and the number of bytes Unichar is variable.
The string created by default is a constant string of the Nsconstantstring class.


Second, the commonly used methods
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
Nsautoreleasepool*pool=[[nsautoreleasepool Alloc]init];


string declaration, assignment, conversion
NSString *[email protected] "This is A string A";
NSString *[email protected] "This is string B";
NSString *res;
Res=[nsstring STRINGWITHSTRING:STR1];
NSLog (@ "with:%@", res);
RES=[STR1 STRINGBYAPPENDINGSTRING:STR2];
NSLog (@ "appending:%@", res);
NSLog (@ "Lowercase of str2:%@", [str2 lowercasestring]);
NSLog (@ "Uppercase of str2:%@", [str2 uppercasestring]);


String interception
NSLog (@ "Length of str1 is:%lu", [str1 length]);
NSLog (@ "First 3 chars of str1:%@", [str1 Substringtoindex:3]);
NSLog (@ "Chars from index 5 of str1:%@", [str1 substringfromindex:5]);
NSLog (@ "Chars from index 8 through 13:%@", [[str1 substringfromindex:8]substringtoindex:6]);
NSLog (@ "Chars from index 8 through 13:%@", [str1 Substringwithrange:nsmakerange (8,6)]);


string comparison
if ([str1 isequaltostring:str2]) {
NSLog (@ "STR1==STR2");
} else {
NSLog (@ "STR1!=STR2");
}
Nscomparisonresult Compareresult;
COMPARERESULT=[STR1 COMPARE:STR2];
if (compareresult==nsorderedascending) {
NSLog (@ "STR1&LT;STR2");
} else if (compareresult==nsorderedsame) {
NSLog (@ "STR1=STR2");
} else {
NSLog (@ "STR1&GT;STR2");
}


String Lookup
Nsrange SubRange;
SUBRANGE=[STR1 rangeofstring:@ "string A"];
NSLog (@ "String is at index%lu,length is%lu", subrange.location,subrange.length);
SUBRANGE=[STR1 rangeofstring:@ "string B"];
if (subrange.location==nsnotfound) {
NSLog (@ "String not Found");
} else {
NSLog (@ "String is at index%lu,length is%lu", subrange.location,subrange.length);
}


[Pool drain];
return 0;
}

Stringwithstring creates and returns a string object by copying a string from the given string object. The syntax is "+ (ID) stringwithstring: (NSString *) astring".

Stringbyappendingstring appends the given string to the accepted string and returns the appended new string. The syntax is: "-(NSString *) stringbyappendingstring: (NSString *) astring".

lowercasestring returns the lowercase character of the string, and the syntax is "-(NSString *) lowercasestring".

Uppercasestring returns the uppercase of the string, with the syntax "-(NSString *) uppercasestring".

Length returns the number of Unicode characters. The syntax is "-(nsuinteger) Length", Nsuinteger represents an unsigned number of shapes.

Substringtoindex returns a character that is from the first character (the index of the first character is 0) until the specified index character (excluding the specified index character), and returns the new truncated string. The syntax is "-(NSString *) Substringtoindex: (Nsuinteger) Anindex".

Substringfromindex returns a substring that starts with the character of the specified index (including the specified index character) until the end of the string. The syntax is "-(NSString *) Substringfromindex: (Nsuinteger) Anindex".

Substringwithrange returns a substring of the specified range. The syntax is "-(NSString *) Substringwithrange: (Nsrange) Arange". The index range relies on the Nsrange object to specify.

Isequaltostring determines whether two strings are equal and returns a Boolean value, with the syntax "-(BOOL) isequaltostring: (NSString *) astring".

Compare returns an object that compares the result, with the following syntax: "-(Nscomparisonresult) Compare: (NSString *) astring". Nscomparisonresult has three cases, indicating whether the given number is greater than (nsorderedascending), equal to (nsorderedsame) or less than (nsordereddescending) the value of the receiver. The Compare method is case-sensitive, and the Caseinsensitivecompare method is not case-sensitive.

Rangeofstring finds the specified string in the accepted string, and returns the first occurrence of the range if there is one. This range is represented by a struct variable, where the value of the struct member location represents the starting index, and the struct member length represents the substring's lengths. If not, the location value of the returned range is nsnotfound.

Obj-c just adds a little "special corpus" to the C language, so you can use printf () instead of NSLog (). However, we recommend using NSLog because it adds features such as timestamps, date stamps, and auto-append line breaks (' \ n ').

An array member of 1.OC is any object pointer similar to the linked list structure in C (nil ending) all array operations cannot be crossed
The OC array is divided into immutable array nsarray variable arrays Nsmutablearray



Nsarray

Nsarray * array = [[Nsarray alloc]initwithobjects:@ "one", @ "one", @ "three", nil];
Get array members by subscript (subscript starting from 0)
NSLog (@ "%@", [array objectatindex:0]);


Gets the number of valid members of an array (excluding nil)
NSLog (@ "%ld", [array Count]);

for (i = 0; i < [array count]; i++) {
Traversing an array (C method)
NSLog (@ "%@", [array objectatindex:i]);
}


(OC) View array contents (send an description message to the array first, and then send a description message to each member)
NSLog (@ "%@", array);


Creating an Array object is equivalent to copying
Nsarray * array1 = [[Nsarray Alloc]initwitharray:array];


Creating an Array object is equivalent to copying
Nsarray * Arry2 = [Nsarray Arraywitharray:array];


Positive Order Enumerator
Creates an enumerator that assigns the address of each element of an array to the enumerator one at a time, and then establishes an association (the enumerator can only be used to read the group members)
Enumeration when an array is created with a certain association (modify monitor/iterator) limit enumeration while cannot modify elements can only be read and cannot be written
Nsenumerator * Enumer = [array objectenumerator];


ID obj;
The first loop assigns the first element of the array to the second loop of obj to assign the second array element to obj
while (obj = [Enumer nextobject]) {
Iterating through an array
NSLog (@ "%@", obj);
}

Fast enumeration first loop assigns the first element of the array to the OB second loop assigns the second element of the array to the OB until nil (can only be read and cannot be changed)
For (ID ob in array) {
NSLog (@ "%@", OB);
}



Reverse output Array (create reverse enumerator the first loop assigns the last element to obj)
Nsenumerator * enumer1 = [array reverseobjectenumerator];
while (obj = [Enumer1 nextobject]) {
NSLog (@ "%@", obj);
}

if ([obj Iskindofclass:[dog class]])
Gets whether the type of the class is an object of the specified class
if ([obj Ismemberofclass:[dog class]]) {
}


2. Non-variable groups

----------------------------String Lookup----------------------------
Nsarray * array = [[Nsarray alloc]initwithobjects:@ "one", @ "one", @ "three", @ "one", nil];
Nsuinteger index = [array indexofobject:@ "one123"];
Returns the first found array member corresponding to the subscript cannot find the return Nsnotfound
index = [Array indexofobject:@ "one" Inrange:nsmakerange (1, 3)];
Find within a specified range
if (Index! = nsnotfound) {
NSLog (@ "%ld", index);
}


----------------------------extract to form a new array----------------------------
Nsarray * array1 = [array Objectsatindexes:[nsindexset indexsetwithindexesinrange:nsmakerange (1, 3)];
"Digital Collection"
Nsindexset This is a number collection class
[Nsindexset Indexsetwithindexesinrange:nsmakerange (1, 3)] produces a set of numbers


3. Variable

Nsmutablearray * array = [[Nsmutablearray alloc]initwithobjects:@ "one", @ "one", @ "three", @ "four", nil];
Inserts an element at the end of an array
[Array addobject:@ "five"];


Inserts an element in an array-specified subscript position (cannot be crossed, maximum value is length)
[Array insertobject:@ "six" atindex:5];


Deletes the specified element (all occurrences of the array will be deleted)
[Array removeobject:@ "six"];


Deletes the specified element within the specified length from the specified subscript position
[Array removeobject:@ "Inrange:nsmakerange" (0, 3)];


Delete last Element
[Array Removelastobject];


Delete all elements
[Array removeallobjects];


Replaces the specified subscript position element with the specified element
[Array replaceobjectatindex:3 withobject:@ "ios"];


Swaps the two elements of a specified subscript
[Array exchangeobjectatindex:0 withobjectatindex:3];


4. String segmentation and splicing


@ "" Empty string Object

---------------------A string split instance---------------------
NSString * ptr = @ "I am a Man";


Return a string as a whole as a split condition to a nsarray non-variable group
Nsarray * array = [ptr componentsseparatedbystring:@ ""];


If modified, convert Nsarray to Nsmutablearray
Nsmutablearray * array1 = [Nsmutablearray Arraywitharray:array];


To split a character in a string as a segmentation condition
Nsarray * array2 = [ptr componentsseparatedbycharactersinset:[nscharacterset charactersetwithcharactersinstring:@ "," ]];

"Character Set"
Nscharacterset This is a character set.


Converts a string into a character set
[Nscharacterset charactersetwithcharactersinstring:@ ","]


---------------------string Concatenation instance---------------------
NSString * str = [array componentsjoinedbystring:@ ""];
If the split condition appears at the beginning or the end, an empty string @ "" will appear, and if not, it will need to be converted to nsmutablestring to process the empty string.
FUNC1: [Array1 removeobject:@ ""];
Find empty string to delete directly
Func2:for (id obj in array1) {
if ([obj length] = = 0)
The length of the empty string is 0
if ([obj isequaltostring:@ ""])
Compare to empty string (string is not = = comparison, use function)
}

NSString usage, object-c arrays and string concatenation and segmentation

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.