I have a string that has the following value: " "OneV", "TwoV", "ThreeV" "
I was wondering if there was a way to take this string and convert it into an array that would have the follwing value: ["OneV", "TwoV", "ThreeV"]
Asked
Active
Viewed 89 times
-3

Eric Aya
- 69,473
- 35
- 181
- 253

Anthony Martini
- 11
- 3
-
which language are you using? what is the type of your string? are they all grouped in a single variable? type of the variable? – ameerosein Mar 28 '19 at 02:17
-
@ameerosein The language is Swift. It's in the tags of the question. – Eric Aya Mar 28 '19 at 12:42
4 Answers
0
Try this:
let aString = " \"OneV\", \"TwoV\", \"ThreeV\" "
let newString = aString.replacingOccurrences(of: "\"", with: "")
let stringArr = newString.components(separatedBy: ",")
print(stringArr)
If the sting not contains "
inside string then
let aString = "OneV,TwoV,ThreeV"
let stringArr = aString.components(separatedBy: ",")
print(stringArr)

Faysal Ahmed
- 7,501
- 5
- 28
- 50
0
swift
let str = "\"OneV\", \"TwoV\", \"ThreeV\""
let ary = str.components(separatedBy: ",")

SodaGun Legendary
- 93
- 6
0
To split a string into an array, you can use
string.split(separator: ",")
This will turn string from "1,2,3,4,5" to ["1","2","3","4","5"]

Salvadorio
- 1
- 2
0
You could traverse the string with two pointers and look for characters between two double quotes (or any character of your choice) :
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
}
And here are some use cases :
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: ",") //[]

ielyamani
- 17,807
- 10
- 55
- 90