【问题标题】:Swift find the end index of a word within a stringSwift 在字符串中查找单词的结束索引
【发布时间】:2020-03-08 12:34:51
【问题描述】:

我有一个字符串。 我在那个字符串里有一个词

我想基本上摆脱字符串和单词中的所有内容。 但是我想保留字符串中单词之后的所有内容。 这个词和字符串可以是动态的。

这是我目前得到的,我发现很难找到在线资源来解决这个问题。

错误:

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

这是我的代码

            var bigString = "This is a big string containing the pattern"
            let pattern = "containing" //random word that is inside big string
            let indexEndOfPattern = bigString.lastIndex(of: pattern) // Error here
            let newText = bigString[indexEndOfPattern...]
            bigString = newText // bigString should now be " the pattern"

【问题讨论】:

  • 你说“错误”。这是非常有用的。查看您的屏幕并发布确切的错误消息。而且你的方法不起作用。您想找到“包含”一词的范围,然后删除该范围的结束索引之前的所有内容。
  • 我首先在帖子顶部发布了错误。代码中的“错误”是指这是上述错误显示的地方。是不是没有像其他语言一样的子字符串的String子函数?

标签: swift swift3 swift4


【解决方案1】:

考虑范围界限lastIndex(of 期望单个Character

var bigString = "This is a big string containing the pattern"
let pattern = "containing" //random word that is inside big string
if let rangeOfPattern = bigString.range(of: pattern) {
    let newText = String(bigString[rangeOfPattern.upperBound...])
    bigString = newText // bigString should now be " the pattern"
}

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多