2012-06-17 53 views
-1

我正在为学校创建一个iOS项目,它可以与化学反应一起使用。基于条件的单独字符串

用户将有一个文本字段中插入这样的方程:

的Fe3O4 + CO = 3FeO + CO2

我的目标是此分离成基于一些条件件:

- 找到大写字母,然后测试下一个字符是否也是大写字母(例如:Fe)。 - 查找每个元素的最后一个字符之后是否有数字。 - 找到一个+符号意味着一个不同的组件。

当然,我并没有要求代码,但我会感谢一些帮助。

在此先感谢。

+0

有几种不同的方法可以帮助你。看NSString的文档,你会找到几个帮助你找到特定字符的索引或范围的文档。它可能也值得看看“正则表达式”或“正则表达式”谷歌将帮助你在那里。 – Dancreek

+0

会做。谢谢! –

回答

1

您可以通过“=”独立字符串和“+”,然后检查字符是小写字母或大写字母

检查这个代码

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

现在你将有做自己的计算和字符串操作,但你有一个良好的开端好运:)

+0

非常感谢! –

+0

你是最受欢迎的:) –

0

是指这样的:isdigit,isupper,islower
试试这个:

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


    } 
}