如果我有一个类似于Slave Machine 2: X.X.X.X
java.lang.NumberFormatException: For input string: "X.X.X.X"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.<init>(Integer.java:867)
的字符串,我需要获取以下数组:"Hello world (this is Sam)"
和以下["Hello world", "this is Sam"]
什么是在Swift中实现此目的的最佳方法? / p>
答案 0 :(得分:1)
不确定你是否仍然需要这个,但你可以试试这个。
let originalString = "Hello world (this is Sam) Hello world (this is Sam) (this is Sam) Hello world Hello world (this is Sam)"
let newArr = originalString.components(separatedBy: ["(", ")"])
var finalArr = [String]()
for (index, value) in newArr.enumerated() {
if (index + 1) % 2 == 1 {
finalArr.append(contentsOf: value.components(separatedBy: " ").filter { $0 != "" })
}
else {
finalArr.append(value)
}
}
print(finalArr) //["Hello", "world", "this is Sam", "Hello", "world", "this is Sam", "this is Sam", "Hello", "world", "Hello", "world", "this is Sam"]
答案 1 :(得分:0)
关于第一种情况,您可以使用括号分隔字符串作为分隔符。然后,omittingEmptySubsequences
将删除进入拆分的任何空字符串。最后,修剪任何分割元素上留下的任何空格或新行。
let splittedText = text.split(omittingEmptySubsequences: true) { separator in
return separator == "(" || separator == ")"
}.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
答案 2 :(得分:0)