0
1

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.

Stringで指定した文字数を抜き出す

Last updated at Posted at 2020-06-01

Sample

var sampleText = "0123456789"

let targetStart = sampleText.index(sampleText.startIndex, offsetBy: 2)
let targetEnd   = sampleText.index(sampleText.startIndex, offsetBy: 5)
let substring   = sampleText[targetStart...targetEnd]
print(substring)  // 2345

Reference

Practice

  • 前述の内容を基に、複数行のテキストを指定した行数に整形する関数を作りました。
    • ただしWord Wrapは考慮していません。
import Cocoa


/// テキストを指定した行数に整形する
/// - Parameters:
///   - text: 対象のテキスト
///   - maxLineNumber: 整形したテキストの最大行数
/// - Returns: 最大行数以下に整形されたテキスト
func createArrangedText(for text: String, maxLineNumber: Int) -> String {
    var lines = [String]()
    
    // 行ごとに分割する
    // また空行がある場合は削除する
    text.enumerateLines { (line, stop) -> () in
        let arranged_line = line.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        if arranged_line.count > 0 {
            lines.append(arranged_line)
        }
    }
    
    if maxLineNumber < lines.count && maxLineNumber > 0 {
        let oneLineText = lines.joined()
        lines = []
        
        let numberOfCharacterByLine = oneLineText.count / maxLineNumber  // 1行あたりの文字数
        
        var targetStart   = oneLineText.index(oneLineText.startIndex, offsetBy: 0)
        var targetEnd     = oneLineText.index(oneLineText.startIndex, offsetBy: numberOfCharacterByLine)
        let targetVeryEnd = oneLineText.index(oneLineText.endIndex,   offsetBy: 0)
        
        for i in 0..<maxLineNumber {
            let newLine: String
            if i == maxLineNumber - 1 {
                // 最終行は割り切れなかった字数文長くなる
                newLine = String(oneLineText[targetStart..<targetVeryEnd])
            } else {
                newLine = String(oneLineText[targetStart..<targetEnd])
                // 次のインデックス取得のために値を更新する
                targetStart = oneLineText.index(targetStart, offsetBy: numberOfCharacterByLine)
                targetEnd   = oneLineText.index(targetEnd,   offsetBy: numberOfCharacterByLine)
            }
            
            lines.append(newLine)
        }
    }
    
    return lines.joined(separator: "\r\n")
}

// from https://lipsum.sugutsukaeru.jp/index.cgi
let inputText =
"""
ここは場合常にその相違式というのの後よりするないな。
どうしても結果をお話者はたとい大した鑑定なでなどを認めるが致したがも参考ありますですながら、どうには片づけませあっないた。

自分をおらで事もけっしてその間のまあなますな。

とにかく嘉納さんに忠告個性そう講演に聞いなくこの世その例外だれか享有にとかいうご教育たうですですば、
こういうたくさんも私か西洋底でいるて、大森さんののの人の私に何でもかでもお相当となっで私鶴嘴にご発展よりするようにせっかくお話が勤まりましでしと、
"""

print(createArrangedText(for: inputText, maxLineNumber: 4))

/*
ここは場合常にその相違式というのの後よりするないな。どうしても結果をお話者はたとい大した鑑定なでなどを認めるが致した
がも参考ありますですながら、どうには片づけませあっないた。自分をおらで事もけっしてその間のまあなますな。とにかく嘉納
さんに忠告個性そう講演に聞いなくこの世その例外だれか享有にとかいうご教育たうですですば、こういうたくさんも私か西洋底
でいるて、大森さんののの人の私に何でもかでもお相当となっで私鶴嘴にご発展よりするようにせっかくお話が勤まりましでしと、
*/
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?