我有一个具有以下值的字符串:“” OneV“,” TwoV“,” ThreeV“”
我想知道是否有办法将这个字符串转换成具有以下值的数组:[“ OneV”,“ TwoV”,“ ThreeV”]
答案 0 :(得分:0)
尝试一下:
let aString = " \"OneV\", \"TwoV\", \"ThreeV\" "
let newString = aString.replacingOccurrences(of: "\"", with: "")
let stringArr = newString.components(separatedBy: ",")
print(stringArr)
如果字符串在字符串中不包含"
,则
let aString = "OneV,TwoV,ThreeV"
let stringArr = aString.components(separatedBy: ",")
print(stringArr)
答案 1 :(得分:0)
迅速
let str = "\"OneV\", \"TwoV\", \"ThreeV\""
let ary = str.components(separatedBy: ",")
答案 2 :(得分:0)
要将字符串拆分为数组,可以使用
string.split(separator: ",")
这会将字符串从“ 1,2,3,4,5”转换为[“ 1”,“ 2”,“ 3”,“ 4”,“ 5”]
答案 3 :(得分:0)
您可以使用两个指针遍历字符串,并在两个双引号(或您选择的任意字符)之间的之间寻找字符:
func substrings(of str: String, between char: Character) -> [String] {
var array = [String]()
var i = str.startIndex
while i < str.endIndex {
while i < str.endIndex, str[i] != char {
i = str.index(after: i)
}
if i == str.endIndex { break }
i = str.index(after: i)
var j = i
while j < str.endIndex, str[j] != char {
j = str.index(after: j)
}
guard j < str.endIndex else { break }
if j > i { array.append(String(str[i..<j])) }
i = str.index(after: j)
}
return array
}
这是一些用例:
let s1 = "\"OneV\", \"TwoV\", \"ThreeV\""
substrings(of: s1, between: "\"") //["OneV", "TwoV", "ThreeV"]
let s2 = "\"OneV\", \"TwoV\", \"Thr"
substrings(of: s2, between: "\"") //["OneV", "TwoV"]
let s3 = "|OneV|, |TwoV|, |ThreeV|"
substrings(of: s3, between: "|") //["OneV", "TwoV", "ThreeV"]
let s4 = "abcdefg"
substrings(of: s4, between: ",") //[]