从字符串中删除一些行

时间:2017-03-26 15:39:47

标签: swift string

我有一个字符串:

first line
second line

first line

first line
second line

first line

如何从此字符串中删除secondlinesSecondlines总是不同的,firsts。只有它们之间的划分是\n\n

2 个答案:

答案 0 :(得分:1)

import Foundation

let string = "first line\n"
           + "second line\n"
           + "\n"
           + "first line\n"
           + "\n"
           + "first line\n"
           + "second line\n"
           + "\n"
           + "first line"

func removeSecondLines1(string: String) -> String {
    let tokens = string.components(separatedBy: "\n")

    var deletedString = tokens[0]
    for i in 1...tokens.count - 1 {
        if tokens[i] == "" || tokens[i - 1] == "" {
            deletedString = deletedString + "\n" + tokens[i]
        }
    }
    return deletedString
}

func removeSecondLines2(string: String) -> String {
    let tokens = string.components(separatedBy: "\n\n")

    var deletedTokens = [String]()
    for token in tokens {
        deletedTokens.append(token.components(separatedBy: "\n")[0])
    }
    return deletedTokens.joined(separator: "\n\n")
}

print(removeSecondLines1(string: string))
print(removeSecondLines2(string: string))

两者都会输出

first line

first line

first line

first line

答案 1 :(得分:1)

只是为了获得有关正则表达式的解决方案:

let string = "first line\nsecond line\n\nfirst line\n\nfirst line\nsecond line\n\nfirst line"

let pattern = "\\n[^\\n]+\\n\n"
let result = string.replacingOccurrences(of: pattern, with: "\n\n", options: .regularExpression)
print(result)