22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS8] Swiftで文字列の接頭・接尾が任意の文字列と一致しているか確認する方法

Posted at

Swiftで任意の文字列の数をカウントする方法をサンプルコードを利用して説明します。
・本サンプルは配列の文字列を検索対象としています
・方法としては2通りあり、以下の関数を利用します

hasPrefix:接頭が一致 => true
hasSuffix:接尾が一致 => true

まず、検索対象となる配列 chargeを生成します。

let charge = [
    "Yamada: Japanese: Monday",
    "Yamada: English:  Tuesday",
    "Yamada: Math:     Wednesday",
    "Tanaka: Japanese: Thursday",
    "Tanaka: English:  Friday"
]

 

hasPrefix:接頭が一致

大文字、小文字も一致しないといけません
var yamada_Count      = 0 // yが大文字の"Yamada"を検索
var yamadaSmall_Count = 0 // yが小文字の"yamada"を検索
for subject in charge {
if subject.hasPrefix("Yamada") {
++yamada_Count      // "3"
}
if subject.hasPrefix("yamada") {
++yamadaSmall_Count // "0"
}
}

先頭から1文字ずつ判定していきます
var ya_Count   = 0    // "ya"を検索
var yama_Count = 0    // "yama"を検索

for subject in charge {
    if subject.hasPrefix("Ya") {
        ++ya_Count    // "3"
    }
    if subject.hasPrefix("Yama") {
        ++yama_Count  // "3"
    }
}

 

hasSuffix:接尾が一致

hasPrefixと同じ性質を持ち、接尾から判定していきます
var monday_Count = 0 // "Monday"を検索
var day_Count    = 0 // "day"を検索
for subject in charge {
if subject.hasSuffix("Monday") {
++monday_Count  // "1"
}
if subject.hasSuffix("day") {
++day_Count     // "5"
}
}

 

 

22
18
0

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
22
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?