Swift - String Prefix and Suffix

Introduction

To check if a string starts with a particular string prefix, use the hasPrefix() method:

Demo

var url: String = "www.apple.com"
var prefix = "http ://"
if !url.hasPrefix(prefix) {
    url = prefix + url//from w  ww. j av  a 2s  . co m
}
print(url)

Here, the hasPrefix() method takes in a String argument and returns true if the string contains the specified string prefix.

You can use the hasSuffix() method to check whether a string contains a particular string suffix:

Demo

var url2 = "https://developer.apple.com/"

var suffix = "/"
if url2.hasSuffix(suffix) {
    print("URL ends with \(suffix)")
} else {/*from  w  ww .  j a  va  2 s  .c o  m*/
    print("URL does not end with \(suffix)")
}

The hasPrefix() and hasSuffix() methods work correctly with Unicode characters as well:

Demo

var str = "voila" + "\u{300}"
var suffix = "\u{300}"
if str.hasSuffix(suffix) {
    print("String ends with \(suffix)")
} else {//  ww w  .  jav  a 2  s.c o  m
    print("String does not end with \(suffix)")
}

Related Topic