2
3

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.

swift2 で 固定長分割

Posted at

なんか、もっと良い方法があると思うんだけど、思いつかないので力技で実装です。

String+Splitter.swift


extension String {

  /** 文字列を固定長で分割する
  - Parameter len: 分割する長さ
  - Parameter handle: 分割ごとに呼び出される
  */
  public func Splitter(len: Int, handle: ((cut: String,isLast: Bool)->Void)) -> Void
  {
    var idx = self.startIndex.advancedBy(len)
    var sub = self.substringToIndex(idx)
    var other = self.substringFromIndex(idx)
    var dist = other.startIndex.distanceTo(other.endIndex)
    while ( dist>len ) {
      handle(cut: sub,isLast: false)
			idx = other.startIndex.advancedBy(len)
			sub = other.substringToIndex(idx)
			other = other.substringFromIndex(idx)
			dist = other.startIndex.distanceTo(other.endIndex)
    }
    handle(cut: sub,isLast: false)
    handle(cut: other,isLast: true)
  }

}


let testString : String = "Hello world"
testString.Splitter(3 , handle: {
	(cut: String,flg: Bool) -> Void in
	LOG("Splitter test \(cut), \(flg)")
})

let testString2 : String = "ハロー 世界よ!"
testString2.Splitter(3 , handle: {
	(cut: String,flg: Bool) -> Void in
	LOG("Splitter test2 \(cut), \(flg)")
})


Splitter test Hel, false
Splitter test lo , false
Splitter test wor, false
Splitter test ld, true

Splitter test2 ハロー, false
Splitter test2  世界, false
Splitter test2  , true

2
3
4

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?