简体   繁体   中英

How to convert String Array to String in Swift

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

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) }

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.

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: ",")
    }
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 Array s of any type

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

You can convert your array into CSV string using this.

let productIDArray = ["1","2","3","4","5"]
let productIDString = productIDArray.joined(separator: ",")
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

游乐场测试

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

在此处输入图片说明

Happy Coding :)

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)\""

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM