Swift拆分字符串的空格要求括号内的文本

时间:2017-12-26 07:46:29

标签: swift

如果我有一个类似于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>

3 个答案:

答案 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)

以下是实现这一目标的方法:

let originalString = "Hello world (this is Sam)"
let newArr = originalString.components(separatedBy: ["(", ")"]).filter { $0 != "" }
print(newArr) //["Hello world ", "this is Sam"]

我发布了thisthis帖子来实现它。