Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
59
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@hiroo0529

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

文字列から文字列を取得するには大きく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

59
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
59
Help us understand the problem. What is going on with this article?