Search code examples
objective-ciosstringcharschemistry

Separate String based on condition


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.


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 :)