Question

I'm creating an iOS project for school and it works with chemical reactions.

The user would have a text field to insert the equation like this:

Fe3O4 + CO = 3FeO + CO2

My goal is to separate this into pieces based on some conditions:

-Finding a capital letter and then testing if the next char is also a capital (e.g.: Fe). -Finding if there's a number after the last char for each element. -Finding a + sign means a different component.

I'm not asking for the code, of course, but I'd appreciate some help.

Thanks in advance.

Was it helpful?

Solution

You can seperate the string by the "=" and the "+" and then check if the character is small letter or capital letter

Check this code

NSString *str = @"Fe3O4 + CO = 3FeO + CO2";
NSArray *arr = [str componentsSeparatedByString:@"="];

NSMutableArray *allComponents = [[NSMutableArray alloc] init];

for (NSString *component in arr) {
    NSArray *arrComponents = [component componentsSeparatedByString:@"+"];
    [allComponents addObjectsFromArray:arrComponents];
}

for (NSString *componentInEquation in allComponents) {
    for (int i = 0 ; i < componentInEquation.length ; i++) {
        char c = [componentInEquation characterAtIndex:i];
        if ('A' < c && c < 'Z') {
            //Small letter
            NSLog(@"%c, Capital letter", c);
        }
        else if ('0' < c && c < '9') {
            NSLog(@"%c, Number letter", c);
        }
        else if ('a' < c && c < 'z') {
            NSLog(@"%c, Small letter", c);
        }
        else {
            NSLog(@"%c Every other character", c);
        }
    }
}

Now you will have to do your own calculation and string manipulation but you have a good start good luck :)

OTHER TIPS

Refer this : isdigit, isupper, islower
Try this:

NSString *str = @"Fe3O4 + CO = 3FeO + CO2";
NSArray *allComponents =[str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"+="]];

for (NSString *componet in allComponents) {
    for (int i=0; i<componet.length; i++) {
        if (isdigit([componet characterAtIndex:i])) {
            NSLog(@"%c is Digit",[componet characterAtIndex:i]);
        }else if(isupper([componet characterAtIndex:i])) {
            NSLog(@"%c is uppercase",[componet characterAtIndex:i]);
        }else if (islower([componet characterAtIndex:i])) {
            NSLog(@"%c is lowercase",[componet characterAtIndex:i]);
        } else{
            NSLog(@"Every other character ");
        }


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