0

I need to convert a String array into single String.

This is my array:

["1","2","3","4","5"]

I need to get this:

"["1","2","3","4","5"]"

3
  • This is not an exact duplicate. Commented Sep 12, 2018 at 11:08
  • i saw this question already your link provide answer without array i want array please have a look Commented Sep 12, 2018 at 11:09
  • 2
    Inside the enclosing double quotes, double quotes needs to be escaped. So, your "["1","2","3","4","5"]" cannot be a valid string in any possible use cases. For what do you want the single string? Commented Sep 12, 2018 at 11:24

7 Answers 7

4

This should work.

let string = ["1","2","3","4","5"]

let newString = "\"[\"" + string.joined(separator: "\",\"") + "\"]\""

print(newString) // Prints "["1","2","3","4","5"]"

Edit: The best way is to use @vadian's answer. Albeit, this doesn't seem like a valid use case.

Sign up to request clarification or add additional context in comments.

21 Comments

getting the same array ["1","2","3","4","5"]
@Jhony but as a single string. You want the string to enclose in double quotes as well?
This is an horrible hack you should tell OP to use the proper tools
@Jhony kindly remove the accepted mark and mark vadian's answer accepted. You just need to append quotes on both sides of that answer to get what you need. My answer is not wrong but not the way to solve your problem.
@RakeshaShastri The string printed with debugDescription is exactly the expected string in the question (except the necessary virtually added backslashes).
|
3

The result is a JSON string so use JSONEncoder

let array =  ["1","2","3","4","5"]
do {
    let data = try JSONEncoder().encode(array)
    let string = String(data: data, encoding: .utf8)!
    print(string.debugDescription) // "[\"1\",\"2\",\"3\",\"4\",\"5\"]"
} catch { print(error) }

2 Comments

getting ["1","2","3","4","5"] i want this array in quoted ""
It is in double quotes, believe me. See the edited answer.
1

Try this code for swift 4

 override func viewDidLoad() {
        super.viewDidLoad()

        let strArray = self.getString(array: ["1", "2", "3"])
        print(strArray)

        // Do any additional setup after loading the view, typically from a nib.
    }

    func getString(array : [String]) -> String {
        let stringArray = array.map{ String($0) }
        return stringArray.joined(separator: ",")
    }

Comments

0
extension Array {

    var fancyString: String {
        let formatted = self.description.replacingOccurrences(of: " ", with: "")
        return "\"\(formatted)\""
    }
}

let array = ["1", "2", "3", "4", "5"]
print(array.fancyString) //"["1","2","3","4","5"]"

Note: this solution will work with Arrays of any type

let ints = [1, 1, 3, 5, 8]
print(ints.fancyString) // "[1,1,3,5,8]"

Comments

0

You can convert your array into CSV string using this.

let productIDArray = ["1","2","3","4","5"]
let productIDString = productIDArray.joined(separator: ",")

Comments

0

If you want from ["1","2","3","4","5"] to "["1","2","3","4","5"]" then check

You can do this in simple way, Please try this

 let arr = ["1","2","3","4","5"]
 let str = "\"\(arr)\""

enter image description here

5 Comments

Unfortunately this introduces an extra space between the elements.
@RakeshaShastri: Print this on console then show me.
I believe you can do that yourself.
@RakeshaShastri Now check
facepalm sigh
0
func objectToJSONString(dictionaryOrArray: Any) -> String? {
do {
    
    //Convert to Data
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryOrArray, options: JSONSerialization.WritingOptions.prettyPrinted)
    
    //Convert back to string. Usually only do this for debugging
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
        return JSONString
    }
    
} catch {
    print(error.localizedDescription)
}

return nil
}

Output will be

Playground test

Edit for an exact answer

Declare a string extension for string

extension String {
var unescaped: String {
    let entities = ["\0": "\\0",
                    "\t": "\\t",
                    "\n": "\\n",
                    "\r": "\\r",
                    "\"": "\\\"",
                    "\'": "\\'",
                    ]
    
    return entities
        .reduce(self) { (string, entity) in
            string.replacingOccurrences(of: entity.value, with: entity.key)
        }
        .replacingOccurrences(of: "\\\\(?!\\\\)", with: "", options: .regularExpression)
        .replacingOccurrences(of: "\\\\", with: "\\")
}
}

Modified code will be

let array = ["1","2","3","4","5"]

let jsonString = objectToJSONString(dictionaryOrArray: array)

print(jsonString!.debugDescription) // this will print "[\"1\",\"2\",\"3\",\"4\",\"5\"]"

let result = jsonString!.debugDescription.unescaped

print(result)

So Output

enter image description here

Happy Coding :)

5 Comments

This is what OP is looking for but he doesn’t know yet
I am not getting. OP?
Original poster
@vadian answer it is also correct for Swift 4 or later
oh! It depends on OP now.

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.