繁体   English   中英

如何在Swift中将字符串数组转换为字符串

[英]How to convert String Array to String in Swift

我需要将String数组转换为单个String

这是我的数组:

[ “1”, “2”, “3”, “4”, “5”]

我需要得到这个:

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

结果是JSON字符串,因此请使用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) }

这应该工作。

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

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

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

编辑:最好的方法是使用@vadian的答案。 但是,这似乎不是有效的用例。

试试这个代码快速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"]"

注意:此解决方案适用于任何类型的Array

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

您可以使用此将数组转换为CSV字符串。

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
}

输出将是

游乐场测试

编辑确切答案

声明字符串的字符串扩展名

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

修改后的代码将是

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)

所以输出

在此处输入图片说明

快乐编码:)

如果要从["1","2","3","4","5"]"["1","2","3","4","5"]"校验

您可以通过简单的方式执行此操作,请尝试此操作

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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