Hello Programmers, In this post, you will learn how to solve HackerRank Building a Smart IDE: Identifying comments Solution. This problem is a part of the Regex HackerRank Series.
One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the Regex HackerRank Solutions using CPP, JAVA, PYTHON, JavaScript & PHP Programming Languages.

HackerRank Building a Smart IDE: Identifying comments Solution
Problem
Jack wants to build an IDE on his own. Help him build a feature which identifies the comments, in the source code of computer programs. Assume, that the programs are written either in C, C++ or Java. The commenting conventions are displayed here, for your convenience. At this point of time you only need to handle simple and common kinds of comments. You don’t need to handle nested comments, or multi-line comments inside single comments or single-comments inside multi-line comments.
Your task is to write a program, which accepts as input, a C or C++ or Java program and outputs only the comments from those programs. Your program will be tested on source codes of not more than 200 lines.
Comments in C, C++ and Java programs
Single Line Comments:
// this is a single line comment
x = 1; // a single line comment after code
Please note that in the real world, some C compilers do not necessarily support the above kind of comment(s) but for the purpose of this problem let‘s just assume that the compiler which will be used here will accept these kind of comments.
Multi Line Comments:
/* This is one way of writing comments / / This is a multiline
comment. These can often
be useful*/
Input Format
Each test case will be the source code of a program written in C or C++ or Java.
Output Format
From the program given to you, remove everything other than the comments.
Sample Input #00
// my program in C++ #include <iostream> /** playing around in a new programming language **/ using namespace std; int main () { cout << "Hello World"; cout << "I'm a C++ program"; //use cout return 0; }
Sample Output #00
// my program in C++
/** playing around in
a new programming language **/
//use cout
Sample Input #01
/This is a program to calculate area of a circle after getting the radius as input from the user/
include
int main()
{
double radius,area;//variables for storing radius and area
printf(“Enter the radius of the circle whose area is to be calculated\n”);
scanf(“%lf”,&radius);//entering the value for radius of the circle as float data type
area=(22.0/7.0)pow(radius,2);//Mathematical function pow is used to calculate square of radius printf(“The area of the circle is %lf”,area);//displaying the results getch(); } /A test run for the program was carried out and following output was observed
If 50 is the radius of the circle whose area is to be calculated
The area of the circle is 7857.1429*/
Sample Output #01
/This is a program to calculate area of a circle after getting the radius as input from the user/
//variables for storing radius and area
//entering the value for radius of the circle as float data type
//Mathematical function pow is used to calculate square of radius
//displaying the results
/A test run for the program was carried out and following output was observed If 50 is the radius of the circle whose area is to be calculated The area of the circle is 7857.1429/
Precautions
Do not add any leading or trailing spaces. Remove any leading white space before comments, including from all lines of a multi–line comment. Do not alter the line structure of multi-line comments except to remove leading whitespace. i.e. Do not collapse them into one line.
HackerRank Building a Smart IDE: Identifying comments Solution in Cpp
#include<iostream> using namespace std; int main() { string line; bool multi=false; while(getline(cin,line)) { bool printed=false; bool single=false; for(int i=0;i<line.length();i++) { if(line[i]=='/'&&line[i+1]=='/'&&!multi) single=true; else if(line[i]=='/'&&line[i+1]=='*') multi=true; if(single||multi) {cout<<line[i];printed=true;} if(line[i-1]=='\n'&&single) single=false; else if(line[i]=='/'&&line[i-1]=='*'&&multi) multi=false; } if(printed) cout<<endl; printed=false; } }
HackerRank Building a Smart IDE: Identifying comments Solution in Java
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.util.Arrays; public class Solution { static BufferedReader br; static PrintWriter out; static String INPUT = ""; static void solve() throws Exception { StringBuilder sb = new StringBuilder(); while(true){ String line = br.readLine(); if(line == null)break; sb.append(line).append("\n"); } char[] s = sb.toString().toCharArray(); int n = s.length; boolean multiline = false; boolean singleline = false; int start = -1; for(int i = 0;i < s.length;i++){ if(!multiline && !singleline && i+1 < n && s[i] == '/' && s[i+1] == '*'){ multiline = true; start = i; i++; }else if(multiline && !singleline && i+1 < n && s[i] == '*' && s[i+1] == '/'){ multiline = false; out.println(new String(s, start, (i+1)-start+1)); }else if(!multiline && !singleline && i+1 < n && s[i] == '/' && s[i+1] == '/'){ singleline = true; start = i; i++; }else if(singleline && s[i] == '\n'){ singleline = false; out.println(new String(s, start, i-1-start+1)); } } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); br = new BufferedReader(INPUT.isEmpty() ? new InputStreamReader(System.in) : new StringReader(INPUT)); out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); tr(G-S+"ms"); } static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
HackerRank Building a Smart IDE: Identifying comments Solution in Python
# Enter your code here. Read input from STDIN. Print output to STDOUT import collections import re def get_input(): import sys return sys.stdin.read() TEXT = get_input() Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column']) def get_comments(s): # Tokenizing the text token_specification = [ ('COMMENT_SINGLE_START', r'//'), ('COMMENT_SINGLE_END', r"\n"), ('COMMENT_MULTI_START', r'/\*'), ('COMMENT_MULTI_END', r'\*/'), ('QUOTE', r'"') ] # Single regex match... tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification) line = 1 pos = line_start = 0 in_single = in_multi = in_string = False single_start = None multi_start = None string_start = None for match in re.finditer(tok_regex, s): typ = match.lastgroup if not (in_multi or in_single) and typ == "QUOTE": in_string = not in_string elif not (in_multi or in_string) and not in_single and typ == "COMMENT_SINGLE_START": in_single = True single_start = match.start() elif not (in_multi or in_string) and in_single and typ == "COMMENT_SINGLE_END": in_single = False yield s[single_start:match.start()] single_start = None elif not (in_single or in_string) and not in_multi and typ == "COMMENT_MULTI_START": in_multi = True multi_start = match.start() elif not (in_single or in_string) and in_multi and typ == "COMMENT_MULTI_END": in_multi = False yield s[multi_start:match.end()] multi_start = None for comment in get_comments(TEXT): print (comment)
HackerRank Building a Smart IDE: Identifying comments Solution in JavaScript
function processData(input) { var m,i; m = input.match(/\/\/.*$|\/\*(?:.|\n)*?\*\//gm) if (m){ for (i=0;i<m.length;i++){ console.log(m[i]); } } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });
HackerRank Building a Smart IDE: Identifying comments Solution in PHP
<?php $file = file_get_contents("php://stdin"); /* Enter your code here. Read input from STDIN. Print output to STDOUT */ preg_match_all('/\/\*[\s\S]*?\*\/|\/\/.*/',$file,$matches); echo implode($matches[0],"\n"); ?>
Disclaimer: This problem (Building a Smart IDE: Identifying comments) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.