Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to array in objective C?

How to convert string to array in objective C. i.e,I have a string,

NSString *str = @"Hi,How r u";

This should be converted into an array *NSMutableArray arr , where in

arr[0] = "Hi"
arr[1] = ","
arr[2] = "How"
arr[3] = "r"
arr[4] = "u"

Can anybody help with the idea to crack this thing.

like image 499
shasha Avatar asked Oct 10 '11 12:10

shasha


People also ask

Can we convert string to array in C?

1. The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

How do I convert a string to a char?

String to char Javachar[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string. char charAt(int index) : This method returns character at specific index of string.

How do I split a string into character array in Swift?

To split a string to an array in Swift by a character, use the String. split(separator:) function.


4 Answers

NSString *str=@"Hi,How r u"; 
NSArray *arr = [str componentsSeparatedByString:@","];
NSString *strSecond = [arr objectAtIndex:1];

NSMutableArray *arrSecond = [strSecond componentsSeparatedByString:@" "];
NSString *strHow = [arr objectAtIndex:0];
NSString *strAre = [arr objectAtIndex:1];
NSString *strYou = [arr objectAtIndex:2];

[arr removeObjectAtIndex:1];
[arr addObject:@","];
[arr addObject:strHow];
[arr addObject:strAre];
[arr addObject:strYou];  

arr is the desired array.

like image 186
Nitish Avatar answered Sep 30 '22 23:09

Nitish


I guess this link will help you.

NSString *str = @"Hi,How r u";
NSArray *listItems = [str componentsSeparatedByString:@","];
like image 45
Ilanchezhian Avatar answered Sep 30 '22 21:09

Ilanchezhian


You have to do,

NSString *str = @"Hi,How r u";
NSArray *arr = [str componentsSeparatedByString:@" "];

And, in order for this to work as you expect, there should be a white-space between "Hi," and "How". Your string should look like @"Hi, How r u".

like image 45
EmptyStack Avatar answered Sep 30 '22 21:09

EmptyStack


try this

NSString *str2=@"Hi,How r u"; 
    NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]]];
    NSLog(@"%@",arary);

if you want , as a object

NSString *str2=@"Hi,How r u";
    str2 = [str2 stringByReplacingOccurrencesOfString:@"," withString:@" , "];
    NSMutableArray *arary = [[NSMutableArray alloc] initWithArray:[str2 componentsSeparatedByString:@" "]];
    NSLog(@"%@",arary);
like image 45
Narayana Avatar answered Sep 30 '22 21:09

Narayana