Counting the number of if and else excluding the nested if-else

前端 未结 3 863
渐次进展
渐次进展 2021-01-22 05:50

Can anyone tell me how can i write a program where i have to read a c program from a text file and then count the number of if-else statements, excluding the nested if-else. Her

相关标签:
3条回答
  • 2021-01-22 06:21

    If you aren't stuck to Java I would suggest Python pycparser https://github.com/eliben/pycparser . If you have to use Java then check Parsing / reading C-Header files using Java

    0 讨论(0)
  • 2021-01-22 06:29

    In general counting if-else statements the way you've specified is wrong 'cause in a programming language if-else statement is not only line containing if or else (consider 'if' or 'else' words in comments and so on). It's exactly a statement in a language defined by a specific set of rules - grammar. Moreover your code will return successfully from not even a C program, which might not be correct...

    So the ultimate way to solve the problem is to build an AST tree for the input program and traverse it counting only top-level if-else statements.

    There are several tools that can help you with this.

    1. ANTLR
    2. JavaCC

    Both of them can generate language parsers from the specified grammar. You can use these parsers to figure out what you input program consist of.

    The main problem of such approach is finding (creating?) the correct grammar. For example there are lots of grammars for both ANTLR (https://github.com/antlr/grammars-v4) and JavaCC (https://java.net/projects/javacc/downloads/directory/contrib/grammars); but none of them can be used to generate AST - only plain parsing will be produced. On the other hand since you need to count only if-else statements you might be good with parsing only (without AST tree)...

    So at this point there are 2 possible solutions:

    1. Manually update generated by ANTLR/JavaCC parser to count if-else statements.
    2. Find/create a C grammar for ANTLR/JavaCC to produce AST of the input program and traverse it in search for a top-level if-else statements.

    ps: for more info on updating grammars to support AST trees see How to implement JJTree on grammar (JavaCC) and How to output the AST built using ANTLR? (ANTLR).

    0 讨论(0)
  • 2021-01-22 06:39

    Without seeing the original file to read, I would use regex to count the total number of if/else and then count the number of nested if/else. The math for the result should be pretty simple... :)

    0 讨论(0)
提交回复
热议问题