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

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -