【问题标题】:Slice Functionality in Swift?Swift 中的切片功能?
【发布时间】:2021-03-19 22:16:05
【问题描述】:

我在 Swift 中阅读了我的 .zshrc 文件,并想打印出其中的所有别名。

func readFile(path: String) -> Int {
    errno = 0
    if freopen(path, "r", stdin) == nil {
        perror(path)
        return 1
    }
    while let line = readLine() {
        if(line.starts(with: "# alias")){
            print(line);
        }
        // do something with lines
    }
    return 0
}

现在输出是这样的

# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
# alias python="/usr/local/bin/python3.7"
# alias python2="/usr/bin/python2"

我想切掉# alias 我该怎么做? 我是 swift 新手。

提前致谢

【问题讨论】:

  • 检查你的字符串是否有hasPrefix("# alias ")dropFirst(8)字符
  • 感谢您的回答。为什么我必须检查 hasPrefix?在我检查代码之前是否以“# alias”开头
  • 其实是一样的String符合RangeReplaceableCollection
  • Drop first 工作正常。谢谢@LeoDabus。

标签: swift string slice


【解决方案1】:

感谢 Leo Dabus

  • dropFirst(8) 工作!
  • 或查看RangeReplaceableCollection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2011-03-29
    • 2019-03-29
    • 1970-01-01
    • 2017-05-03
    • 2018-09-27
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多