【问题标题】:Separate String based on condition [closed]根据条件分离字符串[关闭]
【发布时间】:2012-06-17 13:38:19
【问题描述】:

我正在为学校创建一个 iOS 项目,它适用于化学反应。

用户将有一个文本字段来插入这样的公式:

Fe3O4 + CO = 3FeO + CO2

我的目标是根据某些条件将其分成几部分:

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

当然,我不是要代码,但我会很感激一些帮助。

提前致谢。

【问题讨论】:

  • 有几种不同的方法可以帮助您。查看 NSString 的文档,您会发现一些旨在帮助您找到特定字符的索引或范围的文档。可能还值得一看“正则表达式”或“正则表达式”谷歌会帮助你。

标签: objective-c ios string chars chemistry


【解决方案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);
        }
    }
}

现在你将不得不自己进行计算和字符串操作,但你有一个好的开始,祝你好运:)

【讨论】:

    【解决方案2】:

    请参考: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 ");
            }
    
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多