Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove comments from Go/C program (simple way)
package main
import bufio "bufio"
import fmt "fmt"
import os "os"
func main() {
var state = "0"
var cache = " "
file, err := os.Open("test.txt")
if err != nil {
fmt.Printf("Error: %s", err)
}
reader := bufio.NewReader(file)
cache = ""
charcode, err := reader.ReadByte()
for err == nil {
character := string(charcode) // To one-symbol string
switch state {
case "0": // Start
switch character {
case "\"":
state = "S"
fmt.Printf("%s", character)
case "/":
state = "2"
cache = character
default:
fmt.Printf("%s%s", cache, character)
cache = ""
}
cache = ""
case "1": // escape symbol inside string
state = "S"
fmt.Printf("%s", character)
case "2": // first slash met
switch character {
case "/":
state = "C"
cache = ""
case "*":
state = "MC"
cache = ""
default:
state = "0"
fmt.Printf("%s%s", cache, character)
cache = ""
}
//cache = character
case "3": // star met inside multiline comment
switch character {
case "/":
state = "0"
default:
state = "MC"
}
case "S": // String
switch character {
case "\"":
state = "0"
case "/":
state = "1"
}
fmt.Printf("%s", character)
case "C": // Comment
switch character {
case "\n":
state = "0"
fmt.Printf("%s", character)
}
case "MC": // Multiline comment
switch character {
case "*":
state = "3"
}
}
charcode, err = reader.ReadByte()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment