LoginSignup
3

More than 3 years have passed since last update.

【Swift4】文字列の最初または最後の文字が任意の文字がチェックする

Last updated at Posted at 2018-03-18

環境

  • Swift5

本題

たまに文字列の最初の文字が任意の文字かチェックしてから処理を行うことがある。
それがこちら。

ソースコード
let str = "アスタリスク"

if str.hasPrefix("ア") {
    print("OK!")
}else {
    print("NG!")
}

if str.hasSuffix("ク") {
    print("OK!")
}else {
    print("NG!")
}
実行結果
OK!
OK!

複数文字列のチェックも可能らしい…  つよい。

ソースコード
let str = "アスタリスク"

if str.hasPrefix("アスタ") {
    print("OK!")
}else {
    print("NG!")
}

if str.hasSuffix("リスク") {
    print("OK!")
}else {
    print("NG!")
}
実行結果
OK!
OK!

文字列に対してチェックしたい時にどうぞ!

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
3