简体   繁体   中英

how to add each character of a NSString into a NSArray?

I am looking for a way to pass a NSString, which contains 4 charcters that in whole represent a 4 digit number like 0741, I have been looking around and keep coming across this function

myArray = [dataString componentsSeparatedByString:@"\r\n"];

componentsSeparatedByString... what can I do if my components are not separated?

Well, after checking out the link posted below I found NSRange, and have managed to get it working perfectly with this solution below, however it feels abit drawn out and maybe abit more bulky than it needs to be... let me know what you think and what improvements I could make.

NSRange MyOneRange = {0, 1};
    NSRange MyTwoRange = {1, 1};
    NSRange MyThreeRange = {2, 1};
    NSRange MyFourRange = {3, 1};

    NSString *firstCharacter = [[NSString alloc] init];
    NSString *secondCharacter = [[NSString alloc] init];
    NSString *thridCharacter = [[NSString alloc] init];
    NSString *fourthCharacter = [[NSString alloc] init];

    firstCharacter = [myFormattedString substringWithRange:MyOneRange];
    secondCharacter = [myFormattedString substringWithRange:MyTwoRange];
    thridCharacter = [myFormattedString substringWithRange:MyThreeRange];
    fourthCharacter = [myFormattedString substringWithRange:MyFourRange];


    NSLog(@"%@, %@, %@, %@", firstCharacter, secondCharacter, thridCharacter, fourthCharacter);

To improvise on your approach,

NSRange theRange = {0, 1};
NSMutableArray * array = [NSMutableArray array];
for ( NSInteger i = 0; i < [myFormattedString length]; i++) {
    theRange.location = i;
    [array addObject:[myFormattedString substringWithRange:theRange]];
}

You have many options... there's the - (unichar)characterAtIndex method, to start. I suggest reading the NSString documentation (there's a section of methods called "Getting Characters and Bytes").

Something like this should work nicely:

NSString *dataString = @"0741";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[dataString length]];
for (int i = 0; i < [dataString length]; i++) {
    NSString *singleCharacter  = [NSString stringWithFormat:@"%c", [dataString characterAtIndex:i]];
    [characters addObject:singleCharacter];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM