import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class TrimTest{
public static void main(String args[]) throws IOException{
String[] token = new String[0];
String opcode;
String strLine="";
String str="";
try{
// Open and read the file
FileInputStream fstream = new FileInputStream("a.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
//Read file line by line and storing data in the form of tokens
if((strLine = br.readLine()) != null){
token = strLine.split(" ");// split w.r.t spaces
token = strLine.split(" "||",") // split if there is a space or comma encountered
}
in.close();//Close the input stream
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
int i;
int n = token.length;
for(i=0;i<n;i++){
System.out.println(token[i]);
}
}
}
如果输入MOVE R1,R2,R3 根据空格或逗号分割并将其保存到数组 token[] 中 我想要输出为: 移动 R1 R2 R3
提前致谢。
最佳答案
尝试token = strLine.split("|,")
。
split
使用正则表达式作为参数,正则表达式中的 or
是 |
。您还可以使用character class就像 [\\s,]
等于 \\s|,
并且意味着 \\s
= 任何空格(如普通空格、制表符、换行符)或逗号”。
关于java - 我可以这样做 - token=str.split (""| |",");,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690456/