LoginSignup
0
1

More than 1 year has passed since last update.

Swift文字列検索/置換まとめ

Last updated at Posted at 2022-09-02

何度も忘れては検索してしまうため、まとめ。随時更新。

対象文字列

var targetString = "My name is Swift Ganbaru Man, I'm a guy studying Swift."

特定の文字列で始まっているか?

targetString.contains("Swift") // true
targetString.contains("Python") // false

特定の文字列で終わっているか?

targetString.hasSuffix(".") // true
targetString.hasSuffix("!!") // false

全体置換

// My name is Python Ganbaru Man, I'm a guy studying Python.
targetString.replacingOccurrences(of: "Swift", with: "Python")

// My name is Swift Ganbaru Woman, I'm a lady studying Swift.
targetString.replacingOccurrences(of: "Man", with: "Woman").replacingOccurrences(of: "guy", with: "lady")

一つ目だけ置換

let range = targetString.range(of: "Swift")
// My name is Objective-C Ganbaru Man, I'm a guy studying Swift.
targetString.replacingCharacters(in: range!, with: "Objective-C")
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