gpt4 book ai didi

ios - 从字符串中删除空格和多行?

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:08 24 4
gpt4 key购买 nike

我有一个字符串,像这样:

"  \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n       tjhfhdf \n      "

我想要的结果是:

"assddd\nadjffffdd\ntjhfhdf". 

1:我使用 trimmingCharacters 删除了开头和结尾:

let title = "  \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n       tjhfhdf \n".trimmingCharacters(in: .whitespacesAndNewlines)

2: 去除空格

let result = title.replacingOccurrences(of: " ", with: "")

但是,如何保留字符之间的第一个“\n”并删除其他“\n”?

最佳答案

你可以找到两个或多个连续的换行符一个正则表达式,并用一个换行符替换它们特点。示例:

let s1 = "AA\n\nBB\nCC\n\n\n\n\nDD"
let s2 = s1.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)

print(s1.debugDescription) // "AA\n\nBB\nCC\n\n\n\n\nDD"
print(s2.debugDescription) // "AA\nBB\nCC\nDD"

适用于您的情况:

let title = "  \n assddd\n\n\n\n\n adjf fff dd \n\n\n\n       tjhfhdf \n      "

let result = title.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "\\n{2,}", with: "\n", options: .regularExpression)

print(result.debugDescription) // "assddd\nadjffffdd\ntjhfhdf"

关于ios - 从字符串中删除空格和多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com