LoginSignup
0
1

More than 5 years have passed since last update.

swift置き換え

Posted at

電卓アプリで置き換えに困ったので備忘録として記載

参照元:Swift実践入門 〜 今からはじめるiOSアプリ開発! 基本文法を押さえて、簡単な電卓を作ってみよう

ViewController.swift
private func formatFormula(_ formula: String) -> String {
    // 入力された整数には`.0`を追加して小数として評価する
    // また`÷`を`/`に、`×`を`*`に置換する
    let formattedFormula: String = formula.replacingOccurrences(
        of: "(?<=^|[÷×\\+\\-\\(])([0-9]+)(?=[÷×\\+\\-\\)]|$)",
        with: "$1.0",
        options: NSString.CompareOptions.regularExpression,
        range: nil
        ).replacingOccurrences(of: "÷", with: "/").replacingOccurrences(of: "×", with: "*")
    return formattedFormula
}

replacingOccurrences(日本語:置換発生) = 置き換えをすること
of を with に変更する

ViewController.swift
private var str:String = "aaa" {
        of: "aaa",
        with: "bbb",
        }
    print(str)
// "bbb" が出力される
}

of: 置き換え前
with 置き換え後
options:完全一致等
例:NSString.CompareOptions.regularExpression(string型.完全一致.半角)
(何もオプションがない場合には.literal)
range:どの範囲を指定するか
指定しない場合には、 nil

参考サイト

参照元
Swift実践入門 〜 今からはじめるiOSアプリ開発! 基本文法を押さえて、簡単な電卓を作ってみよう
Swift 3.0でStringはどうなったか
stringをこねくり回すネタ集 swift 3.0
NSString 比較系メソッド覚書

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