]>
<< The Java Programming Language, Fourth Edition | main | 1.24 基本的な構文エラーチェック >>
#include <stdio.h>
#define BUF_SIZE 1024
int main(void){
char s[BUF_SIZE];
int i, j, len;
int comment1, comment2, quoted1, quoted2;
comment1 = comment2 = quoted1 = quoted2 = 0;
while (fgets(s,BUF_SIZE,stdin)){
for (i = 0; i< strlen(s); i++){
if (quoted1){
if (s[i] == '\\') {
putchar(s[i]);
putchar(s[++i]);
} else if (s[i] == '\"'){
quoted1 = 0;
}
putchar(s[i]);
} else if (quoted2){
if (s[i] == '\\') {
putchar(s[i]);
putchar(s[++i]);
} else if (s[i] == '\''){
quoted2 = 0;
}
putchar(s[i]);
} else if(comment1) {
if (s[i] == '*' && s[i+1] == '/') {
comment1 = 0;
i++;
putchar('\n');
}
} else if(comment2) {
if (s[i] == '\n') {
comment2 = 0;
putchar('\n');
}
} else {
if (s[i] == '\"'){
quoted1 = 1;
putchar(s[i]);
} else if (s[i] == '\''){
quoted2 = 1;
putchar(s[i]);
} else if (s[i] == '/') {
if(s[i+1] == '*') {
comment1 = 1;
i++;
} else if (s[i+1] == '/') {
comment2 = 1;
i++;
} else {
putchar(s[i]);
}
} else {
putchar(s[i]);
}
}
}
}
return 0;
}
def linefind(s,t): #searching symbol "t" expected to be forward of a linefeed
p = s.find(t)
eol = s.find('\n') #if '\n' isn't found, eol = -1
if eol == -1 or p <= eol:
return p
else:
return -1
def commentDeleter(p):
quote3 = 0;
s=''
i=0
while(i < len(p)):
if p[i] == '"':
t = linefind(p[i+1:],'"')
if t == -1: #can't find pairing '"'
raise 'syntax error ---string must be closed with double quotation'
else:
s += p[i:i+t+2] #add "string..."
i = i + t + 2 #2 means ""itself
elif p[i] == "'":
t = linefind(p[i+1:],"'")
if t == -1: #can't find pairing "'"
raise 'syntax error ---string must be closed with quotation'
else:
s += p[i:i+t+2] #add 'string...'
i = i + t + 2 #2 means ''itself
elif i+2 < len(p) and p[i] == '"' and p[i+1] == '"' and p[i+2] == '"':
t = p[i+3:].find('"""')
if t == -1:
raise 'syntax error ---string must be closed with """'
else:
s += p[i:i+t+6] #add """string..."""
i = i + t + 6 #6 means ""","""
elif p[i] == '#':
t = linefind(p[i+1:],'\n')
s += '\n'
i = i + t + 2 #2 means # and '\n'
else:
s += p[i]
i += 1
return s
Python版はPythonのコメントを削除する……ハズ。findは見つからなかったときNoneではなくて -1 を返すのか。正規表現とか使えばもっとスマートになるんだろうか。
http://www.panopticon.jp/mt/mt-tb.cgi/28
コメントする