string - 从汇编中的读取输入中删除尾随换行字符

标签 string assembly stdin nasm

我最近一直在自学汇编,我认为 NASM 汇编器及其语法是最有效且最易于使用的。我目前正在使用标准输入和输出;然而,我不知所措,因为我需要从我正在读取的字符串中删除换行符(分别是回车符、换页符、换行符、- 0xd、0xc 和 0xa)。考虑以下因素:

    section .data
;; ...
    section .bss
input:  resb    255
 .len:  equ     $ - input

    section .text
    global  _start

_start:
    ;; Display message prompting for input, then...
    mov     edx, input.len
    mov     ecx, input
    mov     ebx, 0
    mov     eax, 3
    int     0x80

目前,我希望删除尾随换行符。考虑以下伪代码:

if the last character in `input` is 0xa or 0xc or 0xd:
    subtract the last character from `input`
repeat until false

我很可能已经说清楚了,但这里有一个与上述伪代码等效的 Python:

while input[-1] is "\r" or input[-1] is "\f" or input[-1] is "\n":
    input = input[:-1]

最佳答案

这不是特别优雅或高效,但它可能提供一个起点:

jcomeau@intrepid:/tmp$ cat test.nasm ; nasm -f elf -o test.o test.nasm; ld -o test test.o; ./test
    section .bss
input:  resb    255
 .len:  equ     $ - input

    section .text
    global  _start

_start:
    ;; Display message prompting for input, then...
    mov     edx, input.len
    mov     ecx, input
    mov     ebx, 0
    mov     eax, 3
    int     0x80  ;read in from stdin
    call    rstrip
    mov     edx, eax  ;count
    mov     ebx, 1  ;stdout
    mov     eax, 4
    int     0x80  ;write out
    mov     eax, 1
    xor     ebx, ebx
    int     0x80
rstrip:
    dec     eax  ;convert 1-based length to 0-based pointer
.loop:
    cmp     byte [ecx + eax], 0xa
    je      .chop
    cmp     byte [ecx + eax], 0xc
    je      .chop
    cmp     byte [ecx + eax], 0xd
    je      .chop
.done:
    inc     eax  ;convert pointer back to length
    ret
.chop:
    mov     byte [ecx + eax], 0
    dec     eax
    jns     .loop
    jmp     .done
this is a test
this is a testjcomeau@intrepid:/tmp$

关于string - 从汇编中的读取输入中删除尾随换行字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10271159/

相关文章:

Python:str.split() - 是否可以只指定 "limit"参数?

c++ - 将大小设置为结构类型全局变量时出现编译器错误

algorithm - "adjacent"字符串的构建图

assembly - 引导加载程序可在模拟器中运行,但不能在真实硬件中运行

BASH - 在变量中存储标准输入引用 '&0'

javascript - MongoDB shell : reading a line from the console

java - string.replaceAll java 不适用于环视正则表达式?

c - 混合 C 和汇编

c++ - 为什么 asm 中的这种差异对性能很重要(在未优化的 ptr++ 与++ptr 循环中)?

c++ - 使用 QTextStream 以非阻塞方式读取标准输入