我有一个代码:
public static CuttingTemplate parseCuttingTemplate(String[] lines) {
int size = lines.length;
int[] arr = new int[size];
int i;
for(i = 0; i < size; ++i) {
if (i == 0) {
arr[i] = Integer.parseInt(lines[i]);
}
if (i >= 1) {
arr[i] = Integer.parseInt(lines[i]);
}
}
int width = arr[0];
int height = arr[0];
CuttingTemplate ct = new CuttingTemplate(width, height);
return ct;
}
我需要找到一种方法将 .split(";")
和 .split("->")
添加到我的行中。 txt 文件已准备好读取,现在我只需向其中添加一个“规则”,但我不知道该在哪里...
最佳答案
我不确定我完全理解这个问题,但根据您相同的 arr[i] = Integer.parseInt(lines[i]);
行,我假设您想拆分在一种情况下为 ;
,在另一种情况下则在 ->
上拆分。您的 lines[i]
是您要循环的各个 String
行,因此您可以执行以下操作:
if (i == 0) {
String[] splitBySemicolon = lines[i].split(";");
// Get the integer before the ';':
arr[i] = Integer.parseInt(splitBySemicolon[0]);
// or alternatively:
// Get the integer after the ';':
arr[i] = Integer.parseInt(splitBySemicolon[1]);
}
// Minor note: you loop in the range [0, size),
// so you can just use an else here since i cannot be negative
else{
String[] splitByArrow = lines[i].split("->");
// Get the integer before the '->':
arr[i] = Integer.parseInt(splitByArrow[0]);
// or alternatively:
// Get the integer after the '->':
arr[i] = Integer.parseInt(splitByArrow[1]);
}
例如,假设您的lines数组包含["1;header", "3->something", "4->somethingMore"]
,上面的代码(使用[ 0]
用于字符串数组的索引),将导致 arr = [1, 3, 4]
。
但是在不知道您实际的 lines
数组的情况下,我只能猜测您的预期行为。
关于java - 线路问题拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898023/