【问题标题】:How detect first index of each line inside a string with multiple lines?如何检测多行字符串中每一行的第一个索引?
【发布时间】:2018-07-24 07:13:25
【问题描述】:

我有一个string,其中包含多行,每行用不同的分隔符分隔,如\r\n\n 等。所以我使用CharacterSet.newlines 来检测行。但我也想要每个句子的第一个索引。我怎样才能做到这一点?

我使用下面的代码来分隔行:

for (i, mySentence) in sampleString.components(separatedBy: CharacterSet.newlines).enumerated() {
...
}

【问题讨论】:

    标签: swift string newline


    【解决方案1】:

    为此,我将“手动”搜索换行符,以便 当前子字符串及其位置都可用:

    let sampleString = "aaa\naaa\r\nbbb\rccc"
    
    var lines = [String]()
    var positions = [String.Index]()
    
    var pos = sampleString.startIndex // Current position
    while let r = sampleString[pos...].rangeOfCharacter(from: .newlines) {
        if pos != r.lowerBound {
            lines.append(String(sampleString[pos..<r.lowerBound]))
            positions.append(pos)
        }
        pos = r.upperBound // Continue _after_ the newline character
    }
    // The final component:
    if pos != sampleString.endIndex {
        lines.append(String(sampleString[pos...]))
        positions.append(pos)
    }
    

    【讨论】:

      【解决方案2】:

      索引是sampleStringmySentence范围内的lowerBound。变量startIndex 用作跳过已处理行的偏移量。

      let sampleString = "aaa\naaa\n\rbbb\rccc"
      
      var startIndex = sampleString.startIndex
      let firstIndexes = sampleString.components(separatedBy: .newlines).compactMap { line -> String.Index? in
          guard let range = sampleString[startIndex...].range(of: line) else { return nil }
          startIndex = range.upperBound
          return range.lowerBound
      }
      
      print(firstIndexes)
      

      【讨论】:

      • 谢谢。 sampleString 内部可能存在重复的行。因此,按照您提出的方式,我必须将每个范围存储在字典中,并在每个循环中检查它是否在循环内通过。我在寻找更简单的方法
      • 我可以得到一个包含每行第一个索引的第一个索引数组,这是完美的。
      • 我更新了答案以考虑重复行并获取(第一个)索引数组。 i 循环索引实际上没有使用。
      • "aaa\naaa\r\nbbb\rccc" 试试这个——它会在前两行找到相同的索引,然后崩溃。
      • 我也看到了@Martin 提到的问题。
      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多