My input (NSString
)can be ("text")
, {("text")}
or (“text”){{“text”}}
. In all those cases, I have to make sure that an opening delimiter ({
) gets its own closing delimiter (}
).
For example, {{“text”})
should be marked as an error.
I'm trying NSScanner
to accomplish this, and also tried reversing the string and comparing each character looking for its opposite, but've been having some trouble.
What would be the best approach?
This is the latest way I tried going:
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [_expressionTextField.text length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[_expressionTextField.text substringWithRange:subStrRange]];
}
NSString *mystring = _expressionTextField.text;
NSLog(@"%@", reversedString);
for (int i = 0; i < reversedString.length; i++) {
if ([mystring characterAtIndex:i] == [reversedString characterAtIndex:(reversedString.length -i)]) {
NSLog(@"Closed the bracket");
}
}
I had a crack at it, using
NSScanner
. I think this'll be a little faster than vikingosegundo's for very long strings, because I'm just marching straight through one character at a time. There's no searching or substring-making. For most purposes, it probably won't make a difference.I added a method to
NSScanner
to make my life easier. This way we don't have to scan a bunch of characters (since delimiters can be next to each other) and then split them apart into separateNSString
s.A few tests:
You must keep track of the latest delimiter symbols and there occurrence.
You can us a stack for that: through each found opening delimiter on it. When you find the right closing one, delete the last one.
If the delimiter don't match, the bool unbalanced will be YES;