Created
February 13, 2017 00:50
-
-
Save earlonrails/30f50001ce066e2a13c08e229ae2553d to your computer and use it in GitHub Desktop.
Find all the comments in the java code, I did the answer in javascript though
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
"use strict" | |
// https://www.careercup.com/question?id=5663127975755776 | |
// Find all comments in the Java (it could be Python or any other language of your choice) codes that’s parsed in as a string. | |
// You may assume the codes given is valid. | |
// Input is a single string, e.g. | |
// String codes = | |
// “/* file created by aonecode.com\\n” + | |
// “ welcome to the tech blog*/ \\n” + | |
// “//main method\\n” + | |
// “public static void main(String[] args) { \\n“ + | |
// “ System.out.println(“//welcome”); //output\\n” + | |
// “}” | |
// Output is a list of strings | |
// List<String> ret = | |
// [ | |
// “ file created by anecode.com\n welcome to the tech blog”, | |
// “main method”, | |
// “output” | |
// ] | |
var findComments = function(str) { | |
let results = [] | |
let lineComment, blockComment, inAString | |
for (var i = 0; i < str.length - 1; i++) { | |
if (lineComment) { | |
if (str.slice(i, i + 2) == '\\n') { | |
i += 2 | |
results.push(lineComment) | |
lineComment = "" | |
} else { | |
lineComment += str[i] | |
} | |
} else if (blockComment) { | |
if (str[i] == '*' && str[i + 1] == '/') { | |
results.push(blockComment) | |
blockComment = "" | |
i += 2 | |
} else { | |
blockComment += str[i] | |
} | |
} else { | |
if (inAString) { | |
if (str[i] == inAString) { | |
inAString = false | |
} | |
} else { | |
if ((!lineComment && !blockComment) && str[i] == '\"' || str[i] == "\'") { | |
inAString = str[i] | |
} else if (str[i] == '/') { | |
if (str[i + 1] == '*') { | |
i += 2 | |
blockComment = str[i] | |
} else if (str[i + 1] == '/') { | |
i += 2 | |
lineComment = str[i] | |
} | |
} | |
} | |
} | |
} | |
console.log(results) | |
} | |
let codes = "/* file created by blah.com\\n" + | |
"welcome to the tech blog*/ \\n" + | |
"//main method\\n" + | |
"public static void main(String[] args) { \\n" + | |
" System.out.println('//welcome'); //output\\n" + | |
"}" | |
findComments(codes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment