Get String from Substring at a particular range

Viewed 77

I want to write a function where I check the last 3 characters of a string are a part of another string or not, if it does I simply return true, else false.

Example :-

let str1 = "abc"
let str2 = "HiaBC"

What I want to check here is if str1 exists in last characters of str2, irrespective of case sensitiveness.

I tried

str2.contains("HI") // returned true as abc existed, should have returned false as it was not in the last 3 characters of the string.

func checkSubstring(str1:String, str2:String) -> Bool {
    if str2.contains(str1) {
        return true
    }
    return false
}

What I wanted was to somehow apply some range and check if last 3 characters are present in a substring or not.

Anyone can suggest anything?

2 Answers

You can use range(of:) with the appropriate options:

  • .caseInsensitive for case insensitive search,
  • .backwards to start the search from the end of the string, and
  • .anchored to limit the search to the end of the source string.
func checkSubstring(str1:String, str2:String) -> Bool {
    return str2.range(of: str1, options: [.caseInsensitive, .backwards, .anchored]) != nil
}

Example:

print(checkSubstring(str1: "abc", str2: "HiaBC")) // true
print(checkSubstring(str1: "ab", str2: "HiaBC")) // false

There is suffix(3) to consider only the last three characters and caseInsensitiveCompare which is self-explanatory.

func checkSubstring(str1: String, str2: String) -> Bool {
    return str2.suffix(3).caseInsensitiveCompare(str1) == .orderedSame
}
Related