swift - How can I sort an array of strings based on the number of instances a string appears in an element? -


how can sort array of strings based on number of instances string appears in element? example:

let str = "o" let arrayofstrings = ["hot", "only open on tuesdays", "people of earth"]  //sort here  //arrayofstring becomes ["only open on tuesdays", "people of earth", "hot"] 

import foundation let str = "o" var arrayofstrings = ["hot", "only open on tuesdays", "people of earth"]  arrayofstrings.sort {   return $0.components(separatedby: str).count < $1.components(separatedby: str).count }  print(arrayofstrings) // ["hot", "only open on tuesdays", "people of earth"] 

note correct order if sort highest instances last. went least instances show this: string "o" , string "o" 2 different strings count in original array 1, 2, 2. if want compare strings case-insensitively have apply uppercase or lowercase operation comparison.

here result instances of string first, using case-insensitive comparison:

arrayofstrings.sort {   let upper = str.uppercased()   return $0.uppercased().components(separatedby: upper).count >     $1.uppercased().components(separatedby: upper).count }  print(arrayofstrings) // ["only open on tuesdays", "people of earth", "hot"] 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -