複数行の文字列があり、特定の行を読み込んで別の文字列に保存したい。それは私のコードですJavaの文字列から2行目を読み取る方法
上記の文字列textline1とtextline2特定の行を保存します。
複数行の文字列があり、特定の行を読み込んで別の文字列に保存したい。それは私のコードですJavaの文字列から2行目を読み取る方法
上記の文字列textline1とtextline2特定の行を保存します。
あなたは、改行文字で分割することができます
//読み取るには1行目
String line1 = lines[0];
System.out.println(line1);
//を読むには、新しい行に
String[] lines = s.split("\\n");
//を分割します2行目
String line2 = lines[1];
System.out.println(line2);
それは動作していません....これは "1"を出力し、出力しません.... –
私はそれをテストし、それは働いた – Bozho
私は新しいクラスにテストし、あなたは正しいです。それは働いています...私のコードと一致しないものがあります。ありがとうございます –
java.io.LineNumberReader
を使用すると、遭遇する可能性のあるさまざまなタイプの行末を処理するので、ここでも便利です。そのAPI docから:ラインがラインフィード(「\ n」)でのいずれかで終了すると考えられる
は、キャリッジリターン(「\ rを」)、またはキャリッジリターンを改行直後。
例コード:
package com.dovetail.routing.components.camel.beans;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import org.testng.annotations.Test;
@Test
public final class SoTest {
private String text = "example text line 1\nexample text line 2\nexample text line\nexample text line\nexample text line\nexample text line\nexample text line\n";
String textline1 = "";
String textline2 = "";
public void testLineExtract() throws IOException {
LineNumberReader reader = new LineNumberReader(new StringReader(text));
String currentLine = null;
String textLine1 = null;
String textLine2 = null;
while ((currentLine = reader.readLine()) != null) {
if (reader.getLineNumber() == 1) {
textLine1 = currentLine;
}
if (reader.getLineNumber() == 2) {
textLine2 = currentLine;
}
}
assertThat(textLine1).isEqualTo("example text line 1");
assertThat(textLine2).isEqualTo("example text line 2");
}
}
は、あなたがそのような複数行の文字列を宣言することはできませんので、私はそれがちょうど誤植願っています – adarshr
「特定」の行を定義します。 – Jivings
あらかじめ何本の「線」があるのをご存知ですか?第二の行だけを読むことはできますか? –