1

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 2

2

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
5
  • Just a note that this requires Foundation to be imported.
    – Cristik
    Nov 27, 2020 at 11:03
  • Also, this seems to give false positives for corner cases like "aße" and "asse".
    – Cristik
    Nov 27, 2020 at 11:20
  • @Cristik: "ß".caseInsensitiveCompare("ss") == .orderedSame also returns true – probably because both "ß".uppercased() and "ss".uppercased() are equal to "SS".
    – Martin R
    Nov 27, 2020 at 12:04
  • That could be the reason, but on the other hand Vadian's code seems to work for this particular case :)
    – Cristik
    Nov 27, 2020 at 12:47
  • @Cristik: That is more a side effect of his use of suffix().
    – Martin R
    Nov 27, 2020 at 12:53
1

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
}
1
  • Just a note that this requires Foundation to be imported.
    – Cristik
    Nov 27, 2020 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.