Checking Prefix and Postfix of a String in Swift 4

Checking Prefix and Postfix of a string in swift 4:

In this tutorial, we will check how to find if a string is starting with a different sub-string or ends with a different substring in swift. This tutorial is compatible with swift-3, swift-4 and swift-5 . Please leave us a comment if you are not able to run the examples .

Checking if a sub-string is at the beginning of a string :

To check if a string is starting with a sub-string , we can use hasPrefix(prefix: String) method. It returns a boolean . ‘true’ if the string begins with the sub-string, ’false’ otherwise.

let sampleString = "The quick brown fox jumps over the lazy dog"

print (sampleString+"\n")
if(sampleString.hasPrefix("The quick")){
    print ("Above string is starting with \"The quick\" ")
}else{
    print ("Above string is not starting with \"The quick\" ")
}


if(sampleString.hasPrefix("A")){
    print ("Above string is starting with \"A\" ")
}else{
    print ("Above string is not starting with \"A\" ")
}

Output will be :

The quick brown fox jumps over the lazy dog

Above string is starting with "The quick"
Above string is not starting with "A"

Checking if a sub-string is at the end of a string :

Similar to the above example, we can use hasSuffix(suffix: String) to check if a string is ending with a specific sub-string. example :

let sampleString = "The quick brown fox jumps over the lazy dog"

print (sampleString+"\n")
if(sampleString.hasSuffix("lazy dog")){
    print ("Above string is ending with \"lazy dog\" ")
}else{
    print ("Above string is not ending with \"lazy dog\" ")
}


if(sampleString.hasSuffix("A")){
    print ("Above string is ending with \"A\" ")
}else{
    print ("Above string is not ending with \"A\" ")
}

Output :

The quick brown fox jumps over the lazy dog

Above string is ending with "lazy dog"
Above string is not ending with "A"

Both of these comparison are case sensitive and unicode safe. i.e. even if two characters look same but their unicode is different, it will return false.We can say that they do character-by-character canonical equivalence comparison .

You might also like: