swift string modification

swift string modification


1. Replacing
With swift, replacing a character is done by replacingOccurrences
if you want to "12:00" to "12/00" or "1200"
let time = "12:00"
let date = time.replacingOccurrences(of: "/", with: "/")
let hhmm = time.replacingOccurrences(of: "/", with: "")
2. Substring
There is substring type and sbstring type value would be string value.
To get the substring from string, index is required, for example prefix, suffix, split
Here is the example how to do with prefix and suffix
let input = "13:45"
let indexP = input.index(input.startIndex, offsetBy: 2)
let subHH = input.prefix(upTo: indexP)   //it would be 13
let indexS = input.index(input.endIndex, offsetBy: -2)
let subMM = input.suffix(from: indexS) // it would be 45
String(subHH)  // 13 as String
String(subMM) //45 as String

0 件のコメント:

コメントを投稿