LoginSignup
20
19

More than 5 years have passed since last update.

[Swift]Stringから1文字目を取り出す方法メモ

Last updated at Posted at 2014-11-27

たったこれだけのことなのに、

ひと手間必要だったので、メモ

方法

以下のようなString型の変数があるとします。


let str: String = "HelloWorld"

ここから1文字目だけを取り出すには、以下のようにします。


let str: String = "HelloWorld"

let nsStr: NSString = str as NSString

let firstChar: String = nsStr.substringToIndex(1)

println(firstCha)   /// "H"


方法2 ※追記

sora0077 さんにコメントで教えていただきました。

こちらの方が簡単でわかりやすいですね!


var str = "Hello, playground"
//1文字目(0文字目)
str[str.startIndex]

//n文字目
let n = 5
str[advance(str.startIndex, n)]


20
19
3

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
20
19