gpt4 book ai didi

Java读取多行字符串

转载 作者:行者123 更新时间:2023-12-01 18:41:27 24 4
gpt4 key购买 nike

我有一个多行字符串,我想单独显示它们,例如当我只想显示第一个内联时,它将仅显示“apple”

Example display line 1 = orange

我做的如下,可以显示全部,但无法选择显示哪个水果位置

   public static void main(String args[]) {


String fruit = "apple" + "\n" + "orange"+"\n"+"pear";

BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new StringReader(fruit));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

}
}

output:
apple
orange
pear

最佳答案

尝试使用String#split相反,例如...

String fruit = "apple" + "\n" + "orange"+"\n"+"pear";
String[] basket = fruit.split("\n");

这将允许您通过索引单独访问每个元素

关于Java读取多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com