题
好吧,我要解决这个问题,这可能是一个非常复杂的解决方案,但它的第一件事突然出现在我的脑海中。
我需要编写一个汇编语言程序,该程序可以逆转“源”字符串,而无需使用“ target”字符串(温度变量)。这是我的尝试。
INCLUDE Irvine32.inc
.data
source BYTE "This is the source string", 0
count DWORD ?
.code
main PROC
mov ecx, LENGTHOF source
L1:
mov count, ecx ; save our outer loop count
mov al,[source+0] ; get the first character in the string
mov ecx,LENGTHOF source ; set out inner loop count
mov esi, OFFSET source
inc esi
L2:
mov bl,[esi]
dec esi
mov [esi],bl
add esi, 2
loop L2
mov ecx, count
loop L1
mov edx,OFFSET source
call WriteString
exit
main ENDP
END main
现在..“算法”,因为这基本上是:从字符串中取出第一个字符,将所有其他字符移到字符数组中的一个空间中,将您首先取出的字符放入数组的后部。现在,我到了这太复杂的地步。实际上,我如何到达阵列的后面..我想我需要另一个循环?我当然不需要三个循环,甚至不想解决这个问题。
也许我在正确的道路上,甚至不知道。任何建议,提示,代码或其他算法都会有所帮助!
解决方案
你 可以 用两个循环做到这一点。执行第一个循环后,您必须再次进行操作,但长度缩短了一个,以便将当前的第一个(最初是第二个字符)放在 最后第二 位置,仅留下当前的最后(最初是第一个)字符。然后继续前进,直到长度下降到零。
但这很效率,因为您有嵌套环,o(n2)。这是一种更好的算法,仅使用一个循环o(n):
set spointer to point to the first character
set epointer to point to the last character
while epointer is greater than spointer:
save away [spointer] (the character pointed to by spointer) somewhere
copy [epointer] to [spointer]
copy the saved character to [epointer]
add one to spointer
subtract one from epointer
它基本上保持了一个起点和终点指针,该指针最初换了第一个和最后一个字符,然后指针彼此移动。
因此,第二次通过循环,您可以交换第二和第二次角色,第三次是第三和第三次角色等等。
当指针相等时(对于奇数长字符串)或启动指针大于最终指针(对于均匀的长字符串)时,此过程就会停止。
由于这可能是家庭作业(无论如何您似乎都可以加快X86的速度),因此您应该执行将其转换为汇编器的练习。
如果事实证明 不是 要成为作业,您可以将下面的MASM32代码用作基线。请不要试图将其作为您自己的教育工作,因为您几乎可以肯定会被抓住。您会学到更多的东西(作为作业 或者 非家庭工作)如果您自己处理转换,那么如果您在努力效果方面遇到麻烦,我将提供一些倒塌的代码。
.586
.model flat
.data
source byte "This is the source string", 0
.code
_main proc
mov esi, offset source ; load up start pointer.
mov edi, offset source ; set end pointer by finding zero byte.
dec edi
find_end:
inc edi ; advance end pointer.
mov al, [edi] ; look for end of string.
cmp al, 0
jnz find_end ; no, keep looking.
dec edi ; yes, adjust to last character.
swap_loop:
cmp esi, edi ; if start >= end, then we are finished.
jge finished
mov bl, [esi] ; swap over start and end characters.
mov al, [edi]
mov [esi], al
mov [edi], bl
inc esi ; move pointers toward each other and continue.
dec edi
jmp swap_loop
finished:
int 3 ; trap to enter debugger and check string.
; replace with whatever you need.
_main endp
end _main