0

我有一个多行的字符串,我想单独显示它们例如当我只想显示第一个内联时它只会显示“苹果”

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
4

1 回答 1

4

尝试String#split改用,例如...

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

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

于 2013-11-07T04:19:34.420 回答