NSString built in method to compare number of similar characters

Is there a built in method (I can't find it by searching the documentation) to see the number of similar letters in two strings? The order of the letters are not relevant so comparing "abc" to "cad" would have a 66% match for the characters 'c' and 'd'. The number of occurences is also relevant. 'a' should match the first time around, but not on the second since there is only one common 'a' between the two strings. Is there a built in way to do this currently by using some bitwise operation or do I have to loop and manually compare?


You will have to build this yourself, but here is a shortcut for doing it. There is a built-in collection class called NSCountedSet . This object keeps each unique object and a count of how many of each were added.

You can take the two strings and load their characters into two different NSCountedSet collections. Then just check the items in the resulting collections. For example, grab an object from the first NSCountedSet . Check to see if it exists in the second NSCountedSet . The smaller of the 2 counts for that particular letter is how many of those letters that the 2 strings have in common. To shorten the number of iterations, start with the collection with fewer objects and then enumerate through those objects.

Here is Apple's Documentation for NSCountedSet . https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCountedSet_Class/Reference/Reference.html


I am hesitant to say but, there is probably no method out there that fills your requirements. I'd do this:

Create a category on NSString. Lets call it -(float)percentageOfSimilarCharactersForString:(NSString*)targetString

Here's a rough pseudocode that goes into this category:

  • Make a copy of self called selfCopy and trim selfCopy` to contain only unique characters.
  • Similarly trim targetString to unique characters. For trimming to unique characters, you could utilize NSSet or a subclass thereof. Looping over each character and adding to a set would help.
  • Now sort both sets by ASCII values.
  • Loop through each character of targetString -related NSSet and check for it's presence in selfCopy -related NSSet. For this you could use another category called containsString. You can find that here. Every time containsString returns true, increment a pre-defined counter.
  • Your return value would be (counter_value/length_of_selfCopy)*100 .
  • 链接地址: http://www.djcxy.com/p/74010.html

    上一篇: IOS:containsObject检查字符串

    下一篇: 内置NSString方法来比较类似字符的数量