LoginSignup
42

More than 5 years have passed since last update.

Swiftで任意の文字列が含まれるか判定

Last updated at Posted at 2015-11-05
var str : String = "hello Swift"

if str.containsString("Swift") { // -> true
    print("Swiftが含まれる")
}

if str.containsString("swift") { // -> false
    //ここには来ない
}

//大文字小文字を無視させて評価
if str.lowercaseString.containsString("swift") { // -> true
    print("swiftが含まれる")
}

//これも同様にcaseを無視
if str.localizedCaseInsensitiveContainsString("HELLO"){ // -> true
    print("HELLOが含まれる")
}

Swift3

var str : String = "hello Swift"

if str.contains("Swift") { // -> true
    print("Swiftが含まれる")
}

if str.contains("swift") { // -> false
    //ここには来ない
}

//大文字小文字を無視させて評価
if str.lowercased().contains("swift") { // -> true
    print("swiftが含まれる")
}

//これも同様にcaseを無視
if str.localizedCaseInsensitiveContains("HELLO"){ // -> true
    print("HELLOが含まれる")
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42