Mips Assembly 查找字符串中最长单词的地址

Mips Assembly find the address of the longest word in string

我是 Mips 汇编编程的新手。我有这个项目:

首先,我们必须将给定字符串的地址加载到寄存器中。该字符串包含一个句子(一个字符数组),单词用 space 分隔。然后我们必须找到每个单词的长度并将它们的长度与其他单词的长度进行比较。最后我们需要找到长度最长的单词并打印其第一个字母的地址。

例如,如果字符串是:

string: .asciiz "This is a wonderful day"

我们必须 return 存储 w 的地址。

到目前为止我已经写了这个:

.globl main
.text
    main:
      la $a0, string        #Load the address of the string to $a0
      addu $v1, [=11=], $a0     #Initialize the address of the longest word to v1

    exit:                   #Exiting the program
      addiu $v0, $zero, 10  
      syscall

.data
string: .asciiz "This is a wonderful day"   

感谢任何帮助。谢谢

java 中的实现可能是这样的:

int i = 0;
int Counter1 = 0;
int Counter2 = 0;
int address1 = getTheAddressOfCharacter(string[i]); //get the address of     the first letter of the string.
while(string[i] != ' ')  //find the length of the 1st word and store it in counter1.
{
    Counter1 += 1;
    i += 1;
}

int address2 = getTheAddressOfCharacter(string[i]); //get the address of     the second letter of the string.
while(string[i] != '[=12=]')
{
    if(string[i] != ' ')
    {
        if(Counter2 == 0)
            address2 = getTheAddressOfCharacter(string[i]);
        Counter2 += 1;
     }
    else
    {
        if(Counter2 > Counter1) 
        {
            address1 = address2;
            Counter1 = Counter2;
        }
        Counter2 = 0;
    }
    i += 1;
}

编辑工作进展顺利...

更多想法供您探索:

我会将 maxLength 初始化为 0 并保留未分配的地址(结果输出必须遵守这一点并在 (0 == maxLength) 时显示 "no word found",以免触及未定义的内存)。

那么你不需要有两个单独的循环来分别跟踪 first/other 个单词,你可以将第一个单词视为其他任何单词,如果它长于 0 个字符,它将设置当前[maxLength, maxWordAdr] 配对以更正值。解决所有这些 trimmings/etc 的单循环逻辑仍然相当复杂,但是您的 Counter2 的 "in java" 看起来很有希望,并且您将避免将 Counter1 循环固定到同一级别。

重命名变量以更好地描述它们的用途(var1/var2/var3 难以阅读)...我知道这在 asm 指令本身中丢失了,仅使用 rX 寄存器,但这只是另一个原因使所有注释清晰、精简、最新并针对它们描述的代码。

当我编写自己的 ASM 源代码时,我通常在执行单个任务的组指令之前有 1-2 行大注释,或者甚至在特定指令行上有小的提示注释,所以你应该以 at 结尾至少 20% 以上的来源是评论。

经过这样的清理后,只需尝试 运行 将算法用于 2-3 个基本测试输入字符串,如果一切正常,就开始为其编写 asm,应该非常简单。如果不确定,请使用调试器来验证指令是否完全符合您的预期。