我正在制作一个计算器,无法在腐蚀操作数的过程中分离输入字符串。例如: 2 *5-6 + 8 /2。我想要一个包含组件2、5、6、8、2的数组,这样我也可以存储操作器,然后进行相应的排序。请帮帮忙
发布于 2014-11-01 06:03:37
NSString *str=@"2*5 - 6 +8/2"; // assume that this is your str
// here remove the white space
str =[str stringByReplacingOccurrencesOfString:@" " withString:@""];
// here remove the all special characters in NSString
NSCharacterSet *noneedstr = [NSCharacterSet characterSetWithCharactersInString:@"*/-+."];
str = [[str componentsSeparatedByCharactersInSet: noneedstr] componentsJoinedByString:@","];
NSLog(@"the str=-=%@",str);
输出是
the str=-=2,5,6,8,2
发布于 2014-11-01 05:57:56
您可以使用该方法,componentsSeparatedByCharactersInSet:。
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"*-+/"];
NSArray *numbers = [text componentsSeparatedByCharactersInSet:set];
发布于 2014-11-01 06:56:51
您可以获得操作数和操作符的数组,如这样。这假设表达式是有效的,基数为10,以操作数开头和结尾,等等。然后表达式将是操作数、运算符、operands1、operators1等等。
NSString *expression = @"2*5 - 6 +8/2";
// Could use a custom character set as well, or -whitespaceAndNewlineCharacterSet
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *nonWhitespaceComponents = [expression componentsSeparatedByCharactersInSet:whitespaceCharacterSet];
NSString *trimmedExpression = [nonWhitespaceComponents componentsJoinedByString:@""];
// To get an array of the operands:
NSCharacterSet *operatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"+-/*"];
NSArray *operands = [trimmedExpression componentsSeparatedByCharactersInSet:operatorCharacterSet];
// To get the array of operators:
NSCharacterSet *baseTenCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSArray *operators = [trimmedExpression componentsSeparatedByCharactersInSet:baseTenCharacterSet];
// Since expression should begin and end with operands, first and last strings will be empty
NSMutableArray *mutableOperators = [operators mutableCopy];
[mutableOperators removeObject:@""];
operators = [NSArray arrayWithArray:mutableOperators];
NSLog(@"%@", operands);
NSLog(@"%@", operators);
https://stackoverflow.com/questions/26686470
复制相似问题