iOSの電卓アプリを作っています。次の例のように、文字列内で数字と括弧が隣り合っている箇所を見つけられるようにしたいと考えています。
- 23(8+9)
- (89+2)(78)
- (7+8)9
これらの発生の間に文字を挿入できるようにしたいと思います。
- 23(8+9) は 23*(8+9)になります
- (89+2)(78) は (89+2)*(78)になります。
- (7+8)9 は (7+8)*9になります。
iOSの電卓アプリを作っています。次の例のように、文字列内で数字と括弧が隣り合っている箇所を見つけられるようにしたいと考えています。
これらの発生の間に文字を挿入できるようにしたいと思います。
これは、正規表現を使用して一致するパターンを見つけ、必要に応じて「*」を挿入する、私が作成した簡単な関数です。たとえば、2 つの括弧 ")(" または数字と括弧 "5(" または ")3" のいずれかに一致します。たとえば、") 5" のように間にスペースがある場合にも機能します。
ニーズに合わせて機能を自由に調整してください。これが最善の方法かどうかはわかりませんが、うまくいきます。
正規表現の詳細については、NSRegularExpression のドキュメントを参照してください。
- (NSString *)stringByInsertingMultiplicationSymbolInString:(NSString *)equation {
// Create a mutable copy so we can manipulate it
NSMutableString *mutableEquation = [equation mutableCopy];
// The regexp pattern matches:
// ")(" or "n(" or ")n" (where n is a number).
// It also matches if there's whitepace in between (eg. (4+5) (2+3) will work)
NSString *pattern = @"(\\)\\s*?\\()|(\\d\\s*?\\()|(\\)\\s*?\\d)";
NSError *error;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regexp matchesInString:equation options:NSMatchingReportProgress range:NSMakeRange(0, [equation length])];
// Keep a counter so that we can offset the index as we go
NSUInteger count = 0;
for (NSTextCheckingResult *match in matches) {
[mutableEquation insertString:@"*" atIndex:match.range.location+1+count];
count++;
}
return mutableEquation;
}
これは私がそれをテストした方法です:
NSString *result;
result = [self stringByInsertingMultiplicationSymbolInString:@"23(8+9)"];
NSLog(@"Result: %@", result);
result = [self stringByInsertingMultiplicationSymbolInString:@"(89+2)(78)"];
NSLog(@"Result: %@", result);
result = [self stringByInsertingMultiplicationSymbolInString:@"(7+8)9"];
NSLog(@"Result: %@", result);
これは出力されます:
Result: 23*(8+9)
Result: (89+2)*(78)
Result: (7+8)*9
注: このコードは ARC を使用しているため、MRC を使用している場合は、コピーした文字列を自動解放することを忘れないでください。