-3

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"]

2
  • which language are you using? what is the type of your string? are they all grouped in a single variable? type of the variable? Commented Mar 28, 2019 at 2:17
  • @ameerosein The language is Swift. It's in the tags of the question. Commented Mar 28, 2019 at 12:42

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

0

swift

let str = "\"OneV\", \"TwoV\", \"ThreeV\""
let ary = str.components(separatedBy: ",")

Comments

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"]

Comments

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: ",") //[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.