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.
You could always use the NSString method rangeOfString:
to check whether or not your original string contains your desired substring. This method will return an NSRange
with the location of your substring within the original string:
[@"12345" rangeOfString:@"123"]; // Gives range {0, 3}
[@"12345" rangeOfString:@"345"]; // Gives range {2, 3}
[@"12345" rangeOfString:@"678"]; // Gives range {NSNotFound, 0}
This only works if the substring is entirely contained within the original string.
As for the "amount correct," you can use the length
property of the returned range, along with the length of the original string, to see what part of the original string is comprised by the substring. For example:
NSRange r = [@"1234" rangeOfString:@"1"]; // Range {0, 1}
float portion = (float)r.length / (float)[@"1234" length]; // Gives 0.25f
Keep in mind this will fall apart if the substring is repeated - checking for @"1"
as the substring of @"111"
will give only the first occurrence, meaning it'll claim the string is "33% correct" by this method. Depending on your intended use, this may or may not be what you want.
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'.");
}
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.