首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

Python 面試題:移除 C++ 源碼中的註釋

     編輯:C++ 入門

Python 面試題:移除 C++ 源碼中的註釋

題目要求

讀取 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 文字處理能力的優秀展示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved