【问题标题】:How to remove a line containing text from a string in swift如何快速从字符串中删除包含文本的行
【发布时间】:2021-01-08 21:01:34
【问题描述】:

我需要从包含特定文本的字符串中删除行。例如:

"这是 1 行

这是第二个

这是需要删除的第 3 行

这是一条没有"

我需要删除其中包含“已删除”一词的任何行,以便新字符串为:

"这是 1 行

这是第二个

这是一条没有"

理想情况下,它将返回该行中包含的任何整数。所以我现在将没有删除行的字符串,以及另一个变量中的整数 3。

需要删除的行不一定符合任何结构,它们只有关键字和可能的整数。

我尝试过使用

myString.replacingOccurrences(of: "removed", with "") 

但这只会删除该单词而不是整行。

任何帮助将不胜感激,如果需要任何其他信息,请告诉我。提前谢谢你。

【问题讨论】:

    标签: swift string xcode integer substring


    【解决方案1】:

    您可以为此使用filter 函数:

    let lines = ["this is 1 line", "this is the second", "this is line number 3 that needs to be removed", "this is a line that doesn't"]
    
    let filteredLines = lines.filter { $0.contains("removed") == false }
    
    

    结果:

    ["this is 1 line", "this is the second", "this is a line that doesn't"]

    编辑:

    要同时取出数字 3,试试这个:

    let lines = ["this is 1 line", "this is the second", "this is line number 3 that needs to be removed", "this is a line that doesn't"]
    
    var result:  [String] = []
    var number: String = ""
    
    lines.forEach {
        if $0.contains("removed") {
            if let range = $0.rangeOfCharacter(from: CharacterSet.decimalDigits) {
                number = String($0[range])
            }
        }
        else {
            result.append($0)
        }
    }
    
    print(number)
    print(result)
    

    结果:

    3

    ["this is 1 line", "this is the second", "this is a line that doesn't"]

    【讨论】:

    • 感谢您的帮助!我需要将 let number = String($0[range]).intValue 更改为 let number = String($0[range]) 并且效果很好!
    • 我删除了intValue,并从循环中取出了number变量。
    猜你喜欢
    • 2015-11-27
    • 2018-06-28
    • 2021-08-09
    • 1970-01-01
    • 2023-03-19
    • 2014-04-16
    • 2022-11-04
    相关资源
    最近更新 更多