讀取 C++ 源文件,移除所有單行註釋 (// ...) 和多行註釋 (/* ... */),保留代碼結構,輸出處理後的內容。
import sys
bhasCCommentBegin = False
def HandleCPlusPlusComment(lines, i):
"""處理單行註釋 //"""
idx = lines[i].find("//")
if idx != -1:
lines[i] = lines[i][:idx] + "\r\n"
def HandleCComment(lines, i):
"""處理多行註釋 /* */,支援跨行"""
global bhasCCommentBegin
while True:
if not bhasCCommentBegin:
idx = lines[i].find("/*")
if idx != -1:
bhasCCommentBegin = True
idx2 = lines[i].find("*/", idx + 2)
if idx2 != -1:
# 同行開始並結束
lines[i] = lines[i][:idx] + lines[i][idx2+2:-1]
bhasCCommentBegin = False
else:
# 同行開始,未結束
lines[i] = lines[i][:idx] + "\r\n"
return -2 # 繼續處理下一行
else:
return 0 # 本行無多行註釋開始
else:
# 已在多行註釋中,尋找結束
idx2 = lines[i].find("*/")
if idx2 != -1:
bhasCCommentBegin = False
lines[i] = lines[i][idx2+2:-1] # 保留結束後代碼
return -2 # 繼續掃描本行剩餘部分
else:
return -1 # 整行屬於註釋,刪除
def RemoveComment(file):
global bhasCCommentBegin
with open(file, "r") as f:
lines = f.readlines()
i = 0
while i < len(lines):
ret = HandleCComment(lines, i)
if ret == -1:
if not bhasCCommentBegin:
print("There must be some wrong")
del lines[i]
i -= 1
elif ret == 0:
HandleCPlusPlusComment(lines, i)
i += 1
Output(lines)
def Output(lines):
for line in lines:
print(line, end='')
if __name__ == '__main__':
RemoveComment(sys.argv[1])
bhasCCommentBegin 標記是否處於多行註釋中// 在 /* */ 內被誤判)// 或 /*(如 cout << "// not comment"),實際面試可補充狀態機識別字串\r\n 保持格式此題考察字串處理、狀態機設計、邊界情況考慮,是 Python 文字處理能力的優秀展示。