-1

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.

  • There are a few different methods that can help you. Look at the documentation for NSString any you'll find several that are designed to help you find the index or range of specific characters. It might also be worth looking at "Regular Expressions" or "Regex" google will help you there. – Dancreek Jun 17 '12 at 13:49

2 Answers2

1

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

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56
0

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 ");
        }


    }
}
Hector
  • 3,909
  • 2
  • 30
  • 46