gpt4 book ai didi

Swift字符串截取前一段字符

转载 作者:行者123 更新时间:2023-11-30 10:44:28 25 4
gpt4 key购买 nike

如何截取-之前的字符串:

let str = "fist:hello-world";

我想拳头字符串

如果我在 Javascript 中,我将找到遇到的第一个字符,获取其下标并拦截它,但是在 swift 中我该怎么做?

我尝试了一些 api,但不行,你能帮我吗?

最佳答案

要获取“:”或“-”之前的任何内容,您可以将 prefixfirstIndex 结合使用

let firstPart = input.prefix(upTo:input.firstIndex { $0 == ":" || $0 == "-"} ?? input.endIndex)

示例

let examples = ["hello:more stuff", "hello, more-stuff", "hello, more stuff"]

for input in examples {
print(input.prefix(upTo:input.firstIndex { $0 == ":" || $0 == "-"} ?? input.endIndex))
}

输出

hello
hello, more
hello, more stuff

关于Swift字符串截取前一段字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56054775/

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