どうも、ちょげ(@chogetarou)です。
文字列内の文字が何文字目か取得する方法を紹介します。
方法

文字列から特定の文字が何文字目か取得するには、firstIndexメソッドを使います。
まず、文字列からfirstIndexメソッドを呼び出します。
そして、fistIndexメソッドの引数「of」に位置を知りたい文字を指定します。
str.firstIndex(of: char)
firstIndexメソッドは、引数「of」に指定した文字が何文字目かを返します。
使用例
var greeting = "Hello,World"
print(greeting.firstIndex(of: "W")?.utf16Offset(in: greeting)) //Optional(6)
print(greeting.firstIndex(of: "l")?.utf16Offset(in: greeting)) //Optional(2)
オススメの記事
コメント