問題描述
String componentsSeparatedByString 做一次 (String componentsSeparatedByString do one time)
我有一個字符串:let mystring = "key=value=value=value=value"
當我這樣做時:
let ar = mystring.componentsSeparatedByString("=")
我得到:
["key", "value", "value", "value", "value"]
但是我只需要拆分一次,例如 componentsSeparatedByString("=", 1)
,即可得到:
["key", "value=value=value=value"]
## 參考解法 #### 方法 1:
With Swift 2.1, you can use the split function as follows to do what you want:
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
Some example code to test this would be:
let string = "key=value=value=value=value"
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
print(String(result[0])) // "key"
print(String(result[1])) // "value=value=value=value"
方法 2:
This should do the job
func extract(rawData: String) ‑> [String]? {
let elms = rawData.characters.split("=", maxSplit: 1).map { String($0) }
guard let
key = elms.first,
value = elms.last
where elms.count == 2 else { return nil }
return [key, value]
}
Example:
let rawData = "key=value=value=value=value"
extract(rawData) // > ["key", "value=value=value=value"]
Please note the extract
function does an optional array of strings. Infact if the input string does not contain at least an =
then nil
is returned.
The code has been tested with the Swift 2.1 and Xcode Playground 7.1.1.
Hope this helps.
方法 3:
You're probably going to have to write your own custom code to do that, using either NSScanner
or rangeofString:options:range:
EDIT:
Actually, it sounds like the Swift String class's split function, with its maxSplit
parameter, will do what you need. Take a look at the link in Preston's answer.
方法 4:
let mystring = "key=value=value=value=value"
let result = split(mystring as String, { $0 == "=" }, maxSplit: 1, allowEmptySlices: true)
result should now be [key, value=value=value=value]
方法 5:
Try this: (tested and working in playground)
var key = str.substringToIndex(str.rangeOfString("=")!.startIndex)
var value = str.substringFromIndex(str.rangeOfString("=")!.startIndex.advancedBy(1))
var resultingArray = [key, value]
(by Arti、keithbhunter、Luca Angeletti、Duncan C、Shabarinath Pabba、Jeremie D)