如何从 Java 中的文件中拆分字符串
How to split a string from a file in Java
我在 file.txt、|a|b|c|d|
中有一行,我想提取 |
之间的值(结果 a,b,c,d
)
我该怎么做?
来自String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result
: { "boo", "and", "foo" }<br>
o { "b", "", ":and:f" }
使用以下代码:
String[] arr = "|a|b|c|d|".split("\|");
竖线(|
)是正则表达式语言中的特殊字符(split方法以正则表达式为参数),需要进行转义。
您将需要使用类似这样的东西:String[] str = "|a|b|c|d|".split("\|");
鉴于此:
String[] str = "|a|b|c|d|".split("\|");
for(String string : str)
System.out.println(string);
将产生:
//The first string will be empty, since your string starts with a pipe.
a
b
c
d
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(new File(
"file.txt"));
BufferedReader br = new BufferedReader(fr);
String st;
StringBuffer sb = new StringBuffer();
st = br.readLine();
if (st != null) {
StringTokenizer strTkn = new StringTokenizer(st, "|");
while (strTkn.hasMoreElements()) {
sb.append(strTkn.nextElement());
}
}
System.out.println(sb);
}
我在 file.txt、|a|b|c|d|
中有一行,我想提取 |
之间的值(结果 a,b,c,d
)
我该怎么做?
来自String[] split(String regex)
Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result
: { "boo", "and", "foo" }<br> o { "b", "", ":and:f" }
使用以下代码:
String[] arr = "|a|b|c|d|".split("\|");
竖线(|
)是正则表达式语言中的特殊字符(split方法以正则表达式为参数),需要进行转义。
您将需要使用类似这样的东西:String[] str = "|a|b|c|d|".split("\|");
鉴于此:
String[] str = "|a|b|c|d|".split("\|");
for(String string : str)
System.out.println(string);
将产生:
//The first string will be empty, since your string starts with a pipe.
a
b
c
d
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(new File(
"file.txt"));
BufferedReader br = new BufferedReader(fr);
String st;
StringBuffer sb = new StringBuffer();
st = br.readLine();
if (st != null) {
StringTokenizer strTkn = new StringTokenizer(st, "|");
while (strTkn.hasMoreElements()) {
sb.append(strTkn.nextElement());
}
}
System.out.println(sb);
}