【问题标题】:Swift: Remove specific characters of a string only at the beginningSwift:仅在开头删除字符串的特定字符
【发布时间】:2017-01-23 16:10:53
【问题描述】:

我一直在寻找答案,但还没有找到,所以:

例如:我有一个像“#blablub”这样的字符串,我想删除开头的#,我可以简单地删除第一个字符。但是,如果我有一个带有“#####bla#blub”的字符串并且我只想在第一个字符串的开头删除所有#,我不知道如何解决这个问题。

我的目标是得到一个像“bla#blub”这样的字符串,否则用 replaceOccourencies 会很容易......

希望你能帮忙。

【问题讨论】:

标签: ios swift string character


【解决方案1】:
var str = "###abc"

while str.hasPrefix("#") {
    str.remove(at: str.startIndex)
}

print(str)

【讨论】:

    【解决方案2】:

    无正则表达式的解决方案是:

    func removePrecedingPoundSigns(s: String) -> String {
        for (index, char) in s.characters.enumerate() {
            if char != "#" {
                return s.substringFromIndex(s.startIndex.advancedBy(index))
            }
        }
        return ""
    }
    

    【讨论】:

      【解决方案3】:

      我最近为 String 构建了一个扩展,它将从开头、结尾或两者“清除”一个字符串,并允许您指定一组您想要删除的字符。请注意,这不会从字符串内部删除字符,但扩展它来做到这一点相对简单。 (NB 使用 Swift 2 构建)

      enum stringPosition {
          case start
          case end
          case all
      }
      
          func trimCharacters(charactersToTrim: Set<Character>, usingStringPosition: stringPosition) -> String {
              // Trims any characters in the specified set from the start, end or both ends of the string
              guard self != "" else { return self } // Nothing to do
              var outputString : String = self
      
              if usingStringPosition == .end || usingStringPosition == .all {
                  // Remove the characters from the end of the string
                  while outputString.characters.last != nil && charactersToTrim.contains(outputString.characters.last!) {
                      outputString.removeAtIndex(outputString.endIndex.advancedBy(-1))
                  }
              }
      
              if usingStringPosition == .start || usingStringPosition == .all {
                  // Remove the characters from the start of the string
                  while outputString.characters.first != nil && charactersToTrim.contains(outputString.characters.first!) {
                      outputString.removeAtIndex(outputString.startIndex)
                  }
              }
      
              return outputString
          }
      

      【讨论】:

        【解决方案4】:

        Swift2

        func ltrim(str: String, _ chars: Set<Character>) -> String {
            if let index = str.characters.indexOf({!chars.contains($0)}) {
                return str[index..<str.endIndex]
            } else {
                return ""
            }
        }
        

        Swift3

        func ltrim(_ str: String, _ chars: Set<Character>) -> String {
            if let index = str.characters.index(where: {!chars.contains($0)}) {
                return str[index..<str.endIndex]
            } else {
                return ""
            }
        }
        

        用法:

        ltrim("#####bla#blub", ["#"]) //->"bla#blub"
        

        【讨论】:

          【解决方案5】:

          从 OOPer 的响应开始的 swift 3 扩展:

          extension String {
              func leftTrim(_ chars: Set<Character>) -> String {
                  if let index = self.characters.index(where: {!chars.contains($0)}) {
                      return self[index..<self.endIndex]
                  } else {
                      return ""
                  }
              }
          }
          

          【讨论】:

            【解决方案6】:

            正如 Martin R 在上面的评论中已经指出的,正则表达式在这里是合适的:

            myString.replacingOccurrences(of: #"^#+"#, with: "", options: .regularExpression)
            

            您可以将内部的# 替换为您要查找的任何符号,或者如果您要查找多个字符中的一个或一组等,您可以变得更复杂。^ 表示它是开始字符串(所以你不会得到字符串中间的#符号匹配)和+代表“1个或多个前面的字符”。 (* 是 0 或更多,但在这里使用它没有多大意义。)

            请注意,外部哈希符号是将字符串转换为raw String,因此不需要转义(尽管我认为在这个特定示例中实际上不需要转义)。

            我推荐使用正则表达式:https://regexr.com/

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-12-22
              • 1970-01-01
              • 1970-01-01
              • 2022-11-28
              相关资源
              最近更新 更多