Suppose I have a string "167282". How can I check if the string contains "128"? Is there any provision to know the percentage of the 2nd string that matches the first string? (If all the characters of the 2nd string are present in the first string or not.) Please help and thanx in advance.
Use the following:
NSString *compareString = @"128";
NSCharacterSet *compareCharSet = [NSCharacterSet characterSetWithCharactersInString:@"167282"];
NSUInteger strLen = [compareString length];
NSUInteger matchingCount = 0;
for (NSUInteger i = 0; i < strLen; ++i) {
if ([compareCharSet characterIsMember:[compareString characterAtIndex:i]])
++matchingCount;
}
float percentMatching = matchingCount/(float)strLen;
Where matchingCount will be the number of characters in compareString that match a character in @"167282" and percentMatching will be the percent of total characters in compareString that match. This is, as best as I can tell, what you intended with your question - the concept of a percent match wouldn't make any sense otherwise.
You can use NSString's rangeOfString method to find out whether a string contains another string, as suggested by the answers to this question on the Apple Mailing Lists.
if ([@"167282" rangeOfString:@"128"].location != NSNotFound) {
NSLog(@"String contains '128'.");
}
else {
NSLog(@"String doesn't contain '128'.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With