Character replacing in a string
suppose I have string like "this str1ng for test" now开发者_开发问答 i want to check if character at position [i-1] and [i+1] are both alphabet but character at [i] is number, like this example in word "str1ng" then character at position [i] replaced by appropriate alphabet. or vice versa.
I need this for post processing for output of OCR. TQ
You might have an easier time using Regular Expressions.
NSString
are immutable, so you'll have to create a new NSMutableString from it, and mutate this copy, or to allocate a unichar*
buffer, copy data from the NSString, perform the correction, and then recreate a new NSString
from the result. Once you're working on a mutable copy of the string, you can use whatever algorithm you want.
So you'll need to have a function like that:
- (NSString*)correctOCRErrors:(NSString*)string
{
BOOL hasError = NO;
for (int i = 0; i < [string length]; ++ i)
{
if (isIncorrect([string characterAtIndex:i]))
{
hasError = YES;
break;
}
}
if (hasError)
{
unichar* buffer = (unichar*)malloc([string length]);
for (int i = 0; i < [string length]; ++ i)
{
unichar chr = [string characterAtIndex:i];
if (isIncorrect(chr))
chr = correctChar(chr);
buffer[i] = chr;
}
string = [[[NSString alloc] initWithCharactersNoCopy:buffer length:[string length] freeWhenDone:YES] autorelease];
}
return string;
}
You can access character in a NSString
by passing a message charAtIndex:(NSUInteger)index
.
And now you can get the ascii value at the particular index you are interested in and change it according to your requirement.
NSString Ref
Hope this is helpful !
精彩评论