; trailing comments

(define (tc? str)     ; true when a trailing comment is found, else false
  (let loop ((xs (string->list str)) (inquotes #f))     ; initialize loop
    (cond ((null? xs) #f)           ; reached end-of-line without comment
          ((and inquotes (char=? (car xs) #\"))            ; end of quote
            (loop (cdr xs) #f))       ; initialize for next quoted string
          ((and inquotes (char=? (car xs) #\\) (pair? (cdr xs))) ; escape
            (loop (cddr xs) #t))   ; skip backslash and escaped character
          (inquotes (loop (cdr xs) #t))                  ; continue quote
          ((char=? (car xs) #\") (loop (cdr xs) #t))        ; start quote
          ((char=? (car xs) #\#) #t)             ; found trailing comment
          (else (loop (cdr xs) #f)))))                   ; next character

(display (tc? "x = \"# This is fine\""))   (newline)
(display (tc? "\"This \\# is fine too\"")) (newline)
(display (tc? "x = \"\" # This is not\"")) (newline)