Question

I am trying to withdraw values in a string in an iOS app. I have an NSString in the format:

loc: 32 3203 292 293 321

I want to store all five integers into a 5 different int variables. The integers are of varying length. I am currently trying to determine which integer I am at using the space character as a guide, but I am having problems. There must be a simpler way to do it.

Here is what I have:

int length = [locationString length];
    NSMutableString * xStr, * yStr,* zStr, *tiltStr, *panStr;

    int charIndex = -1;
    unichar cur;

    for(i = 3; i < length; i++)
    {
        cur = [locationString characterAtIndex:i];
        if(cur == ' ') charIndex++;
        else
        {
            if(charIndex == 0)
            {
                [xStr appendString:[NSString stringWithCharacters:&cur length:1]];
            }
            else if(charIndex == 1)
            {
                [yStr appendString:[NSString stringWithCharacters:&cur length:1]];
            }
            else if(charIndex == 2)
            {
                [zStr appendString:[NSString stringWithCharacters:&cur length:1]];
            }
            else if(charIndex == 3)
            {
                [tiltStr appendString:[NSString stringWithCharacters:&cur length:1]];
            }
            else if(charIndex == 4)
            {
                [panStr appendString:[NSString stringWithCharacters:&cur length:1]];
            }
        }
    }

    NSLog(@"x String: %@", xStr);
    NSLog(@"y String: %@", yStr);
    NSLog(@"z String: %@", zStr);
    NSLog(@"tilt String: %@", tiltStr);
    NSLog(@"pan String: %@", panStr);

    if(xStr != NULL) xVal = [xStr integerValue];
    if(yStr != NULL) yVal = [yStr integerValue];
    if(zStr != NULL) zVal = [zStr integerValue];
    if(tiltStr != NULL) tiltVal = [tiltStr integerValue];
    if(panStr != NULL) panVal = [panStr integerValue];

But I am getting void strings each time. Anyone else do something like this before?

Thanks

Was it helpful?

Solution 2

I would start with

[locationString componentsSeparatedByString:@" "];

This will give you an array with each string component.

You can then ignore index 0, which would contain @"loc:", and the remaining array indices will contain the data you will use.

OTHER TIPS

I think you should consider using the NSString componentsSeparatedByString API to make your life easier. You'll get a NSArray of strings using [locationString componentsSeparatedByString:@" "] and your integers will be in indeces 1-5

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top