在文本文件中查找字符串。然后得到以下行并需要拆分
Find string inside of the text file. Then getting the following line and need to Split
在文本文件中找到一个字符串。然后得到以下行并需要 Split
我的代码写在这里
import java.util.*; // for Scanner
import java.io.*; // for File and IOException
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File("a.dat");
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
//System.out.println(filename);
if (line.contains(airportcode)) {
System.out.println(line); //1 sout
String[] split = line.split("|");
for (int i = 0; i < split.length; i++) {
String split1 = split[i];
System.out.println(split1);
}
break;
}
}
}}
1 sout 看起来像这样 French Polynesia|HOI|Hao|Tuamotos|Hao Airport
所以在我尝试按此 "|"
拆分之后,它的输出看起来像这样
French Polynesia|HOI|Hao|Tuamotos|Hao Airport
F
r
e
n
c
h
P
o
l
y
n
e
s
i
a
|
H
O
I
|
H
a
o
|
T
u
a
m
o
t
o
s
|
H
a
o
A
i
r
p
o
r
t
BUILD SUCCESSFUL (total time: 5 seconds)
但我需要这样
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
我该怎么办?
问题在于 split
方法采用正则表达式作为参数,您需要转义管道字符以实际拆分 |
并获得正确的结果
String[] split = line.split(Pattern.quote("|"));
或
String[] split = line.split("\|");
使用\|
拆分
演示:
public class Main {
public static void main(String[] args) {
String line = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
String[] split = line.split("\|");
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
}
}
输出:
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
在文本文件中找到一个字符串。然后得到以下行并需要 Split
我的代码写在这里
import java.util.*; // for Scanner
import java.io.*; // for File and IOException
public class FileReadTest {
public static void main(String[] args) throws IOException {
File f = new File("a.dat");
Scanner fin = new Scanner(f);
String airportcode = "HOI";
while (fin.hasNextLine()) {
String line = fin.nextLine();
//System.out.println(filename);
if (line.contains(airportcode)) {
System.out.println(line); //1 sout
String[] split = line.split("|");
for (int i = 0; i < split.length; i++) {
String split1 = split[i];
System.out.println(split1);
}
break;
}
}
}}
1 sout 看起来像这样 French Polynesia|HOI|Hao|Tuamotos|Hao Airport
所以在我尝试按此 "|"
拆分之后,它的输出看起来像这样
French Polynesia|HOI|Hao|Tuamotos|Hao Airport
F
r
e
n
c
h
P
o
l
y
n
e
s
i
a
|
H
O
I
|
H
a
o
|
T
u
a
m
o
t
o
s
|
H
a
o
A
i
r
p
o
r
t
BUILD SUCCESSFUL (total time: 5 seconds)
但我需要这样
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
我该怎么办?
问题在于 split
方法采用正则表达式作为参数,您需要转义管道字符以实际拆分 |
并获得正确的结果
String[] split = line.split(Pattern.quote("|"));
或
String[] split = line.split("\|");
使用\|
演示:
public class Main {
public static void main(String[] args) {
String line = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
String[] split = line.split("\|");
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
}
}
输出:
French Polynesia
HOI
Hao
Tuamotos
Hao Airport