2017-03-01 77 views
1

我目前正在嘗試編寫一個代碼,它接受一個字符串並輸出相同的字符串,不含空格。我的代碼中的所有內容當前都有效,但輸出不會刪除字符串的以前的值。例如,如果輸入是「jack and jill跑上山丘」,則輸出是「jackandjillranupthehill hill」。看起來我的字符串仍然保留着舊的值。有沒有人有任何想法,爲什麼這是這樣做以及如何解決它?在MIPS中從字符串中刪除空格

.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 

回答

0

字符串是NULL終止,你應該將那個終止NULL到您的字符串的新的終端也是如此。

在一個側面說明,你可以做整個事情到位(爲便於C代碼:)

#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); 
} 
0

這是另一種方式來刪除刺痛空間和打印回。簡單地循環字符串並忽略空格。

.text 
main: 
    li $v0, 4  
    la $a0, prompt 
    syscall 

    li $v0, 8  
    la $a0, input 
    li $a1, 100 
    syscall 

    move $s0, $a0 

loop: 
    lb $a0, 0($s0) 
    addi $s0, $s0, 1 
    beq $a0, 32, loop 
    beq $a0, $zero, done  

    li $v0, 11 
    syscall 

    j loop 

done: 
    jr $ra 

    .data 
prompt: .asciiz "Enter a string: " 
input: .space 100