簡體   English   中英

如何在Swift中轉換字符串?

[英]How to convert Strings in Swift?

我有兩種情況需要將字符串轉換為不同格式。

例如:

case 1:
  string inputs: abc, xyz, mno, & llr   // All Strings from a dictionary
  output: ["abc","xyz", "mno", "llr"]  //I need to get the String array like this.

但是當我使用此代碼時:

 var stringBuilder:[String] = [];
 for i in 0..<4 {
   stringBuilder.append("abc"); //Appends all four Strings from a Dictionary
 }

print(stringBuilder); //Output is 0: abc, 1:xyz like that, how to get desired format of that array like ["abc", "xyz"];

實際用法:

let arr = Array(stringReturn.values);
//print(arr)  // Great, it prints ["abc","xyz"];
let context = JSContext()
context?.evaluateScript(stringBuilder)   
let testFunction = context?.objectForKeyedSubscript("KK")
let result = testFunction?.call(withArguments:arr); // Here when I debugger enabled array is passed to call() like 0:"abc" 1:"xyz". where as it should be passed as above print.

其次,如何快速替換轉義字符:我在replaceOccurances(of:"\\\\'" with:"'"); 但其不變。 為什么以及如何逃避該序列。

case 2:
  string input: \'abc\'
  output: 'abc'

要將字典的所有值作為數組獲取,可以使用字典的values屬性:

let dictionary: Dictionary<String, Any> = [
    "key_a": "value_a",
    "key_b": "value_b",
    "key_c": "value_c",
    "key_d": "value_d",
    "key_e": 3
]

let values = Array(dictionary.values)
// values: ["value_a", "value_b", "value_c", "value_d", 3]

使用filter您可以忽略字典中不是String類型的所有值:

let stringValues = values.filter({ $0 is String }) as! [String]
// stringValues: ["value_a", "value_b", "value_c", "value_d"]

有了地圖,你可以改變的值stringValues並應用replacingOccurrences功能:

let adjustedValues = stringValues.map({ $0.replacingOccurrences(of: "value_", with: "") })
// adjustedValues: ["a", "b", "c", "d"]

案例1:我已經實現了此解決方案,希望這可以解決您的問題

   let dict: [String: String] = ["0": "Abc", "1": "CDF", "2": "GHJ"]                
   var array: [String] = []

for (k, v) in dict.enumerated() {
    print(k)
    print(v.value)
    array.append(v.value)  
}
print(array)

情況2:

    var str = "\'abc\'"
    print(str.replacingOccurrences(of: "\'", with: ""))

為什么不嘗試這樣的事情? 對於問題的第1部分,是:

var stringReturn: Dictionary = Dictionary<String,Any>()
stringReturn = ["0": "abc","1": "def","2": "ghi"]
print(stringReturn)

var stringBuilder = [String]()
for i in stringReturn {
  stringBuilder.append(String(describing: i.value))
}
print(stringBuilder)

另外,除非我沒有記錯,否則第2部分似乎很簡單。

var escaped: String = "\'abc\'"
print(escaped)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM