在MIPS中从字符串中删除空格 [英] Removing Spaces from String in MIPS

查看:143
本文介绍了在MIPS中从字符串中删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写一个代码,该代码接受一个字符串,并输出相同的字符串而没有空格.我的代码中的所有内容当前都可以正常运行,但是输出不会删除字符串的先前值.例如,如果输入为"jack and jill跑上山",则输出为"jackandjillranupthehill上山".看来我的字串仍然坚持旧的价值观.有谁知道为什么这样做以及如何解决?

I am currently trying to write a code that takes in a string and outputs that same string with no spaces. Everything in my code currently works, but the outputs don't delete previous values of the string. For example, if the input is "jack and jill ran up the hill", the output is "jackandjillranupthehill hill". It seems that my string is still holding on to old values. Does anyone have any idea why this is doing this and how to fix it?

.data 
string1: .space 100
string2: .space 100
ask: .asciiz "Enter string: "
newstring: .asciiz "New string:\n"

.text

main:
la $a0,ask #ask for string1
li $v0,4
syscall

#load String1
la $a0,string1
li $a1, 100
li $v0,8 #get string
syscall


load:
la $s0,string1  #Load address of string1 into s0
lb $s1, ($s0)   #set first char from string1 to $t1
la $s2 ' '  #set s2 to a space
li $s3, 0   #space count


compare:
#is it a space?
beq $s1, $zero, print   #if s1 is done, move to end
beq $s1, $s2, space #if s1 is a space move on
bne $s1, $s2, save  #if s1 is a character save that in the stack

save:
#save the new string
sub $s4, $s0, $s3, 
sb $s1, ($s4)
j step

space: 
addi $s3, $s3, 1 #add 1 if space

step:
addi $s0, $s0, 1 #increment first string array
lb $s1, ($s0) #load incremented value
j compare



print:
#tell strings
la $a0, newstring
li $v0,4
syscall

#print new string
la $a0, string1
li $v0, 4
syscall

end:
#end program
li $v0, 10
syscall #end

推荐答案

字符串以NULL终止,您也应将该终止NULL移至字符串的新端.

Strings are NULL terminated, you should move that terminating NULL to the new end of your string as well.

顺便说一句,您可以就地完成全部操作(为方便起见,使用C代码:)

On a side note, you could do the whole thing in place (for ease in C code:)

#include <stdio.h>

int main() {
  char string1[100];
  fgets (string1, 100, stdin);
  char *inptr = string1; //could be a register
  char *outptr = string1; //could be a register
  do
  {
    if (*inptr != ' ')
      *outptr++ = *inptr;
  } while (*inptr++ != 0); //test if the char was NULL after moving it
  fputs (string1, stdout);
}

这篇关于在MIPS中从字符串中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆