简体   繁体   中英

How to detect bracet (at the end of line or new line)?

This is my code.

while(in.hasNext()){
        String line = in.nextLine();
        in.hasNextLine();
        if (line.length() >0){
            int k = -1;
            k = -1;
            while(true){
                k = line.indexOf('\n' + "{", k+1);
                if(k<0)break;
                bracketNewLine++;
            }
            k = -1;
            while(true){
                k = line.indexOf(" {", k+1);
                if(k<0)break;
                bracketWithSpace++;
            }
        }
    }

if I have text file

if (...) {
}

and 

if (...)
{
}

output is:

  • bracet end of line are: 1
  • bracet new line are: 1

Thank you for answering.

You read the file line by line. Hence, there is no chance to find the character \\n followed by another character in the same String. Hence, '\\n' + "{" will never be found.

You can do it with simple regex :

for(String line : Files.readAllLines(Paths.get("/path/to/input.txt"))) {
  if(line.matches("\\{.*")) {
    bracketNewLine++;
  }

  if(line.matches(".* \\{")) {
    bracketWithSpace++;
  }
}

You could use some regex like this:

String patternInLine = ".+\\{$";
String patternNewLine = "^\\{":

Pattern p1 = new Pattern(patternInLine);
Pattern p2 = new Pattern(patternNewLine);

while(in.hasNext()) {
    String line = in.nextLine();
    in.hasNextLine();

    Matcher m1 = p1.match(line);
    Matcher m2 = p2.match(line);
    if(m1.match())
    {
        //inLine++;
    }
    else if (m2.match())
    {
        //newLine++;
    }
    else
    {
        //other cases
    }
}

When you use nextLine() method, you already have the source line by line. The only thing you should do is checking those lines in every loop with existing String methods : startsWith() , endsWith() . If we assume that you are correctly obtaining line string in each loop, inside of that while block should be like that:

if(line.startsWith("{"))
    bracketNewLine++;
if(line.endsWith("{"))
    bracketWithSpace++;

PS1 hasNext() method does not assure us that we have one more new line.

PS2 searching a string with fixed size space is not a true approach. You may use regex instead of that : ^[\\s]*{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM