组装中的计数字母

Counting letter in Assembly

前几天开始学习汇编(32位),有一个疑问。 我想创建一个程序,在文本中计算 'x'(仅小写字母)并将其显示在屏幕上(本例 -> 4)。我写了那个,但我被卡住了。我在 'counting' 可以做什么?

运行

gcc -m32 program.s
./a.out

输出

4

我的代码

 .intel_syntax noprefix
  .text
  .global main

main:
  mov eax, offset messg
  push eax
  call counting
  add esp , 4
  //print result
  push eax
  mov eax, offset printf_arg1
  push eax
  call printf
  add esp, 8
exit:
  //return from code
  mov eax, 0

  ret
counting:
// HERE

.data
messg:
  .asciz "x Exemple XText x"
printf_arg1:
  .asciz "%i"

接下来是一个简单的计数代码。

; IN (address) OUT (eax=count) MOD (edx)
counting:
  mov  edx, [esp+4]         ; Address of the text is on the stack right above the return address
  xor  eax, eax             ; Clear the counter to be reported back
  jmp  .first               ; (*)
.test:
  cmp  byte ptr [edx], 'x'
  jne  .next
  inc  eax                  ; Found an 'x'
.next:
  inc  edx                  ; Move to the next string position
.first:
  cmp  byte ptr [edx], 0    ; Are we at the end of the string?
  jne  .test                ; No, go compare for 'x'
  ret

(*) 您始终需要先测试字符串的结尾,因为字符串可能为空!