26
24

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

Swiftで指定した位置の文字列を、簡単に切り出す

Last updated at Posted at 2016-04-02

正直、息をするのも面倒なタイプなので、substringWithRange()の引数にfoo.startIndex.advancedBy(ホゲェ)とかいちいち書くのほんとだるいです。
単純にInt型で_"x〜y文字目"、あるいは"n文字目"_が引数でいいじゃん。

…なので、Extension作った。

以下のコードをまるっとコピペして、プロジェクトに追加すれば使えます。

String+Extension.swift
extension String{
	func substringWithRange(start: Int, end: Int) -> String{
		return self.substringWithRange(Range(self.startIndex.advancedBy(start) ..< self.startIndex.advancedBy(end)))
	}

	func substringWithRange(range: Range <Int>) -> String{
		return self.substringWithRange(Range(self.startIndex.advancedBy(range.startIndex) ..< self.startIndex.advancedBy(range.endIndex)))
	}

	func substringWithRange(position: Int) -> String{
		return self.substringWithRange(Range(self.startIndex.advancedBy(position) ..< self.startIndex.advancedBy(position + 1)))
	}

	func substringToEnd(position: Int) -> String{
		return self.substringWithRange(Range(self.startIndex.advancedBy(position) ... self.endIndex))
	}

	func substringFromEnd(position: Int) -> String{
		return self.substringWithRange(Range(self.endIndex.advancedBy(-position) ... self.endIndex))
	}
}

以下、使用例

var str = "いろはにほへとちりぬるを"

// 範囲指定、指定位置の切り出し
print(str.substringWithRange(8, end:9)) // りぬ
print(str.substringWithRange(1...4))    // ろはにほ
print(str.substringWithRange(12))       // を

// 指定位置から最後まで切り出し
print(str.substringToEnd(5))   // へとちりぬるを

// 最後から数えて指定位置まで切り出し
print(str.substringFromEnd(1)) // るを
26
24
2

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
26
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?