Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 856
HurkNburkS Avatar asked Dec 12 '22 12:12

HurkNburkS


1 Answers

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]];
}
like image 168
Deepak Danduprolu Avatar answered Dec 27 '22 19:12

Deepak Danduprolu