1
1

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 3 years have passed since last update.

Stringで使えるメソッド

Last updated at Posted at 2022-08-07

はじめに

Stringの出力を操作したい時に使えるメソッドを紹介します。
自分がすぐに忘れてしまうので、備忘録です。

hasPrefix

let animal = "cat"

if animal.hasPrefix("c") {  // "c"が接頭辞なのでtrue
    print("dog")
} // dog

prefix(接頭辞)と和訳すると解りやすいです😀

hasSuffix

let animal = "cat"

if animal.hasSuffix("t") { // "t"が接尾辞なのでtrue
    print("dog")
} // dog

これまたsuffix(接尾辞)と和訳すると解る😃

prefix

let animal = "cat"

print(animal.prefix(2)) // ca

接頭辞から2文字目までを抽出します😆

suffix

let animal = "cat"

print(animal.suffix(2)) // at

prefixと逆の挙動です😁

range(of:)

let animal = "cat"

private func confirmIncludeString(animal: String) -> String {
    if animal.range(of: "r") == nil {
        return "animalに(of:)で指定した文字が含まれていません"
    }else {
        return "animalに(of:)で指定した文字が含まれています"
    }
}
print(confirmIncludeString(animal: animal))
 // animalに(of:)で指定した文字が含まれていません

range(of:)は帰ってくる型がRange型なので、サンプルコードみたいに文字列を判定したい時に使えそうですね😯

dropFirst

let animal = "cat"

let animalDeleteString = animal.dropFirst(1)

print(String(animalDeleteString)) // at

dropFirstの引数に指定した数を飛ばして出力してくれます。
Substring型で返ってくるので、String型にキャストしないとエラーになります。😭

dropLast

let animal = "cat"

let animalDeleteString = animal.dropLast(1)

print(String(animalDeleteString)) // ca

dropFirstの最後尾からバージョンですね

まだまだ知らないメソッドが沢山あります😭
都度更新していけたらと思っています!!
以上です。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?