LoginSignup
63
59

More than 5 years have passed since last update.

[iOS] Swiftで文字列から任意の文字列を取得・残す方法

Last updated at Posted at 2014-12-17

文字列から文字列を取得するには大きく2つやり方があります。

・取得元から範囲を指定して、新たに変数へ代入する方法
・取得元から不要な文字列を削除し、任意の文字列を残す方法
 

1 取得元の文字列は不変

・先頭からの取得範囲を指定

関数:substringToIndex(from: String.Index)

let str = "Hello World!"

(str as NSString).substringToIndex(5)             // Hello
str.substringToIndex(advance(str.startIndex, 5))  // Hello
"Hello World!".substringToIndex(5)                // Hello

 

・スタート地点を指定しそれ以降を全て取得

関数:substringFromIndex(to: String.Index)

let str2 = "Hello World!"

(str2 as NSString).substringFromIndex(5)              // World!
str2.substringFromIndex(advance(str2.startIndex, 5))  // World!
"Hello World!".substringFromIndex(5)                  // World!

 

・先頭からの取得範囲を指定

関数:substringWithRange(range: NSRange)

let str    = "Hello World!"

let getStr = (str as NSString).substringWithRange(NSRange(location: 5, length: 7))  // World!
"Hello World!".substringWithRange(NSRange(location: 5, length: 7))                  // World!

 

2 一文字だけ取得

・頭文字

let str = "Hello, World!"
str[str.startIndex]  // "H"

 

・任意の場所

let str = "Hello, World!"
str[advance(str.startIndex, 5)]  // "."

3 取得元の文字列を変える

・指定範囲を削除 = 必要なものを残す

// String型
var str = "Hello World!"
str.removeRange(str.startIndex..<advance(str.startIndex, 5))  // str = " World!"

//MutableString型
let str:NSMutableString = "Hello World!"                     
str.deleteCharactersInRange(NSRange(location: 0,length: 5))     // str = " World!"

 

※こちらの記事を参考にさせていただきました

String.substring〜の使い方
http://qiita.com/takmaru/items/2442ad5eb0f76815e1b3

[Swift]Stringから1文字目を取り出す方法メモ
http://qiita.com/iKichiemon/items/4736110a80dab10177ea

63
59
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
63
59