linux - 在汇编中拆分字符串

标签 linux gcc assembly x86 nasm

我正在使用一个代码来用定界符分割一个字符串,但它保存了我的“右边”,我需要这个词的“左边”。

例如,如果输入是15,20,x,那么输出应该是:

15
20
x

但它告诉我:

15,20,x
20,x
x

这是我正在使用的代码

split:
    mov     esi,edi
    mov     ecx, 0 
    not     ecx    
    mov     al, ','
    cld         
    repne     scasb
    not     ecx
    lea     eax, [ecx-1]

    ;push     eax
    mov     eax, edi
    call     println        ;Here is where I want to print the "left side"
    ;pop     eax

    xchg     esi, edi

    mov     eax, esi
    call     length

    mov     edi, esi
    mov     ecx, eax
    cmp     ecx, 1
    je         fin
    jg         split
    ret
fin:
    ret

最佳答案

repne scasb后ECX的内容由-1变为-4,需要NOT ECX再DEC ECX得到ECX=2(成员“15”的大小)。然后在 ESI 处打印文本的 ECX 字节并重复拆分: 有一个问题:由于最后一个成员“x”没有以逗号结尾,repne scasb 会崩溃。在扫描之前,您应该将 ECX 限制为输入文本的总大小。我用 EuroAssembler 尝试了这个变体:

; Assembled on Ubuntu with
; wine euroasm.exe split.asm
; Linked with
; ld split.obj -o split -e Main -m elf_i386
; Run with
; ./split
       EUROASM
split  PROGRAM Format=COFF, Entry=Main:
        INCLUDE linapi.htm,cpuext32.htm ; Library which defines StdInput,StdOutput.
[.text]
Main:   StdOutput ="Enter comma-separated members: "
        StdInput  aString    ; Read aString from console, return number of bytes in ECX.
        MOV EDI,aString      ; Pointer to the beginning of text.
        LEA EBX,[EDI+ECX]    ; Pointer to the end of text.
split:  MOV ESI,EDI          ; Position of the 1st byte.
        MOV ECX,EBX
        SUB ECX,EDI          ; How many bytes is left in unparsed substring.
        JNA fin:
        MOV AL,','
        REPNE SCASB
        MOV ECX,EDI
        DEC ECX              ; Omit the delimiter.
        SUB ECX,ESI
        StdOutput ESI, Size=ECX, Eol=Yes
        JMP split:
fin:    TerminateProgram
[.bss]
aString DB 256 * BYTE
       ENDPROGRAM split

而且效果很好:

./split
Enter comma-separated members: 15,20,x
15
20
x

关于linux - 在汇编中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55930945/

相关文章:

C++ lambda 在模板的第二次扩展中没有捕获变量?

linux - linux上的共享库问题

c++ - 为什么 gcc 不为我决定内联或不内联这个功能?

c - strcasecmp 实现不打印

c - 在 NASM 中实现 strstr 的问题

regex - 如何通过 Linux CLI 在文件中搜索模式?

linux - 在 linux 服务器上卸载了 PhpMyAdmin,现在 apache 重启给出了这个错误

c# - 如何用 C# .NET 编写程序,在 Linux/Wine/Mono 上运行它们?

linux - 如何在 shell 脚本中保存 "read "错误输出?

assembly - 什么时候应该在 x86 程序集中使用 MOVS 而不是 MOV?