swiftstringswift-playgroundlongest-prefix

longest prefix substring in a string in swift


Check this code on xcode playground

I am trying to get the longest prefix substring from string in swift. This solution is working but I have a question

the min function is not giving me desired "swim" as shortest string

`
var string = "swimftch swim swimftc swill"

let splitArray = string.split(separator: " ")

var shortestString = string
for singleString in splitArray {
    
    //This works fine - gives "swim" as desired
//    if shortestString.count > singleString.count {
//        shortestString = String(singleString)
//    }
    
    //this does not - gives "swill"
    shortestString = min(String(singleString), shortestString)
    print(shortestString)
}

var isPrefixed = false

func checkSubString() {
    for sub in splitArray {
        if sub.contains(shortestString) {
            print(shortestString)
            isPrefixed = true
        } else {
            isPrefixed = false
        }
    }
    if !isPrefixed {
        shortestString.popLast()
        checkSubString()
    } else {
        print(shortestString)
    }
}


checkSubString()
`

Can anyone explain this to me, why min is not returning the shortest substring correctly?

for singleString in splitArray {
    
    //This works fine - gives "swim" as desired
//    if shortestString.count > singleString.count {
//        shortestString = String(singleString)
//    }
    
    //this does not - gives "swill"
    shortestString = min(String(singleString), shortestString)
    print(shortestString)
}

Solution

  • String comparisons in swift does not work based on the character count. Swift strings are compared according to the Unicode Collation Algorithm, which means that:

    1. each string is put into "Unicode Normalization Form D",
    2. the unicode scalar values of these "decomposed" strings are compared lexicographically.

    That's why shortestString.count > singleString.count and shortestString > singleString will not yield the same result.