Android - 读取前两行String

时间:2013-12-15 12:35:24

标签: java android string int

我有一个大字符串(让我们称之为c),如下所示:


12345
67890
some
random
data

有两个变量 - int aint b。 我需要阅读c的第一行并将其值设为a,然后从c读取第二行并将其值设为{{ 1}}。我怎么能这样做?

UPD 我认为这不是使用String []的好方法。 b是非常大的字符串,c方法可以冻结我的应用。还有另一种方法可以解决这个问题吗?

P.S。请原谅我的英语。

1 个答案:

答案 0 :(得分:4)

假设您的字符串为c,其上面的值由linebreak

分隔

使用以下代码:

String lines[] = c.split("\\r?\\n");
int a = Integer.parse(lines[0]);
int b = Integer.parse(lines[1]);

<强>更新

这是一个备用循环,可用于获取第一行和第二行:

boolean found = false;
int position = 0, oldPosition = 0;
int a, b, count = 0;

while(!found) {
    if(c.charAt(position) == '\n') {
        count++;
        if(count == 1) {
            a = Integer.parseInt(c.substring(oldPosition, position));
            oldPosition = position+1;
        }
        if(count == 2) {
            b = Integer.parseInt(c.substring(oldPosition, position));
            found = true;
        }
    }
    position++;
}