Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a nsstring matches another string

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.

like image 956
Bapu Avatar asked May 14 '26 07:05

Bapu


2 Answers

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.

like image 76
Bryan Henry Avatar answered May 15 '26 23:05

Bryan Henry


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'.");
}
like image 20
Steve Harrison Avatar answered May 15 '26 21:05

Steve Harrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!