我正在编写一个程序,从文件中逐行读取代码,并打印出" int"之后的所有内容。
例如:
int x;
int y;
打印出来:
x
y
这是我到目前为止编写的代码
BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"));
String line = null;
while((line = br.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(line);
while(token.hasMoreTokens())
{
String s = null;
s = token.nextToken();
if(s.equals("int"))
{
System.out.println(token.nextToken());
}
}
}
但是,我想要排除要打印的int类型的函数,例如" MyFunction"在这个例子中
x
z
MyFunction(int
y)
x,
y
输入文件:
int x = 137;
int z = 42;
int MyFunction(int x, int y) {
printf("%d,%d,%d\n", x, y, z);
{
int x, z;
z = y;
x = z;
{
int y = x;
{
printf("%d,%d,%d\n", x, y, z);
}
printf("%d,%d,%d\n", x, y, z);
}
printf("%d,%d,%d\n", x, y, z);
}
}
我对java很新,所以请耐心等待。
答案 0 :(得分:0)
试一试。仅适用于类似上面的输入。
while((line = br.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(line);
while(token.hasMoreTokens())
{
String s = null;
String r = null;
s = token.nextToken();
if(token.hasMoreTokens()){ //if s was not last token get next one
r = token.nextToken();
}
if(s.equals("int") && r != null && r.length()<3)
{
System.out.println(r.substring(0, 1)); // just to print x instead of x,
}
}
}
答案 1 :(得分:0)
您也可以试试这个。
while((line = br.readLine()) != null){
String cleaned = line.trim(); //remove leading and trailing white space
String [] parts = cleaned.split(" |\\(");// split using white space or opening brace
if (line.matches("(\\s*)int(\\s*)(\\w+)(,\\s*\\w+)*(;)")){ // check for multiple variable declariation e.g. int a,b,c;
for (int k = 1; k <parts.length; k++){
System.out.println(parts[k]);
}
}
else {
for (int i = 0; i <parts.length-1; i=i+2){
if((parts[i].equals("int")&&parts[i+1].length()<3) ){ //requires variable name length to be one
System.out.println(parts[i+1].substring(0, 1));
}
}
}
}