You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自制编程语言词法分析器开发:字符串索引越界问题求助

解决词法分析器处理注释时的索引越界问题

你这个问题我太熟了!本质就是当注释行是文件最后一行时,后面没有换行符\n,你的while循环会一直把c往上涨,直到超出整个字符串的长度,直接触发索引越界报错。另外还有个隐藏坑:你外层用的是for c in range(len(Program)),这种写法里内部修改c的值根本不会影响外层循环的迭代,下次循环还是会按原来的序列走,很容易导致字符重复处理或者漏处理。

我给你改好代码,顺便把这些坑都填上:

comment = ['//', '/*', '*/']
keyw = ["main", "void"]
br = ['(', ')', '{', '}']
lineCount = 1
temp = ''
flag = False
f = open('Program.C', 'r')
Program = f.read()
f.close()  # 别忘了关闭文件,好习惯

c = 0
length = len(Program)
while c < length:
    current_char = Program[c]
    
    if current_char == ' ':
        c += 1
        continue
    if current_char == '\n':
        lineCount += 1
        c += 1
        continue
    
    # 处理单行注释
    if current_char == '/' and c + 1 < length:
        next_char = Program[c+1]
        if next_char == '/':
            # 跳过整个注释行,直到换行或文件结束
            c += 2  # 跳过//
            while c < length and Program[c] != '\n':
                c += 1
            # 如果最后是换行,要额外加1并更新行号
            if c < length and Program[c] == '\n':
                lineCount += 1
                c += 1
            continue  # 处理完注释直接进入下一轮循环
    
    # 处理括号
    if current_char in br:
        print(lineCount, "Brackets", current_char)
        c += 1
        temp = ''  # 重置临时字符串
        continue
    
    # 处理关键字和标识符
    temp += current_char
    if temp in keyw:
        print(lineCount, "Keyword", temp)
        temp = ''
    c += 1

关键修改点说明:

  • 把外层的for循环改成while循环,这样能完全手动控制c的位置,避免内部修改无效的问题。
  • 在处理注释的while循环里加了c < length的判断,绝对不会越界。
  • 处理完注释后,判断是否遇到换行符,正确更新行号并移动索引。
  • 增加了文件关闭操作,避免资源泄漏。
  • 处理括号后重置了temp,避免残留字符干扰后续关键字判断。

你用这个代码跑你的测试文件Program.C,就不会再报索引越界的错了,而且能正确跳过所有单行注释。

内容的提问来源于stack exchange,提问作者user10542046

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:23:27