How to convert string to array in objective C?

前端 未结 5 1193
不思量自难忘°
不思量自难忘° 2021-02-06 08:35

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 *NS

相关标签:
5条回答
  • 2021-02-06 09:21
    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.

    0 讨论(0)
  • 2021-02-06 09:27

    You can use the NSString method componentsSeparatedByString. Take a look at the reference here.

    0 讨论(0)
  • 2021-02-06 09:38

    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);
    
    0 讨论(0)
  • 2021-02-06 09:40

    I guess this link will help you.

    NSString *str = @"Hi,How r u";
    NSArray *listItems = [str componentsSeparatedByString:@","];
    
    0 讨论(0)
  • 2021-02-06 09:40

    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".

    0 讨论(0)
提交回复
热议问题