用特殊字符分隔字符串

时间:2014-11-01 05:28:37

标签: ios data-structures

我正在制作一个计算器,无法将输入字符串与操作数相对应。 例如:2 * 5 - 6 +8/2。我想要一个包含组件2,5,6,8,2的数组,这样我也可以存储操作符,然后进行相应的排序。请帮忙

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以使用方法componentsPaparatedByCharactersInSet:。

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"*-+/"];
NSArray *numbers = [text componentsSeparatedByCharactersInSet:set]; 

答案 2 :(得分:0)

你可以获得操作数和运算符的数组。这假定表达式有效,基数为10,以操作数等开始和结束。表达式将是操作数[0],运算符[0],操作数[1],运算符[1]等。

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);
相关问题