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"]
-
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– ameerosein2019-03-28 02:17:43 +00:00Commented Mar 28, 2019 at 2:17
-
@ameerosein The language is Swift. It's in the tags of the question.Eric Aya– Eric Aya2019-03-28 12:42:22 +00:00Commented Mar 28, 2019 at 12:42
Add a comment
|
4 Answers
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)
Comments
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: ",") //[]