我有一个大字符串(让我们称之为c
),如下所示:
12345
67890
some
random
data
有两个变量 - int a
和int b
。
我需要阅读c
的第一行并将其值设为a
,然后从c
读取第二行并将其值设为{{ 1}}。我怎么能这样做?
UPD 我认为这不是使用String []的好方法。 b
是非常大的字符串,c
方法可以冻结我的应用。还有另一种方法可以解决这个问题吗?
P.S。请原谅我的英语。
答案 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++;
}