0

我想简单、正确、高效地执行这个操作。另外我不想手动将字符串拆分为行。

这是我希望的(something like this but it is not particularly critical)。

var string = someMultilneString;
var reader = new StringReader(string);
while(true) {
  var line = reader.readLine();
  if(line == null) {
    break;
  }
  // work with line
}

如果这个 ( or similar to this) 是不可能的,那为什么?

PS 另外,请不要提供比这个例子更糟糕的答案。因为这种方式是众所周知的,但这是一个糟糕的设计,总是编写自己的实现来支持常见的输入和输出操作。

List<String> StringToLines(String text) {
  var source = text.replaceAll('\r\n', '\n');
  source = source.replaceAll('\r', '\n');
  var lines = source.split('\n');
  var lenght = lines.length;
  if(lenght > 0 && lines[lenght - 1].isEmpty) {
    lines.length--;
  }

  return lines;
}
4

1 回答 1

3

只需逐行拆分字符串:

String str = someMultilineString;
str.split("\n").forEach((line) {
    // work with line
});

这是最简单的方法,它应该足够快(除非你的字符串很大)。请参阅文档

如果你真的想要你的成语,你可以创建自己的类:

class StringReader {
    String str;
    int i;
    int start = 0;
    StringReader(this.str);

    String readLine() {
        // we've exhausted the string
        if (this.start < 0) return null;

        String ret;
        this.i = this.str.indexOf("\n", this.start);
        if (this.i < 0) {
            // this is the last line
            ret = this.str.substring(this.start);
        } else {
            ret = this.str.substring(this.start, this.i);
        }
        // if this is the last line, start will be -1
        this.start = this.i;
        return ret;
    }
}

var reader = new StringReader(someMultilineString);
for (var str = reader.readLine(); str != null; str = reader.readLine()) {
    // do something with line
}

但是这个split版本更简单,更惯用。

于 2013-07-20T06:09:12.717 回答