Search code examples
stringmipscountingwords

Count number of words from a string input


In the following code, 32 is for ASCII space character. I am facing a problem in moving inside the string:

.data
para: .asciiz " "
buffer: .space 250
ctr: .word 0
.text
.globl main
.ent main
main:addi $t3,$0,32
li $t8,1 
la $a0,para
li $v0,8
syscall
li $t0,0
loop:bge $t0,$a0,exit
add $t1,$a0,$t0
lb $t2,0($t1)
beq $t2,$t3,counter
addi $t0,$t0,1
j loop
counter:addi $t8,$t8,1
addi $t0,$t0,1
j loop 

exit:sw $t8,ctr
li $v0,10
syscall
.end main

Solution

  • I found the answer today, I was comparing the array before loading individual chars:

    .data
    msg: .asciiz"Enter\n"
    buffer: .space 250
    ctr: .word 0
    
    .text
    .globl main
    .ent main
    main:addi $t3,$0,32    #$t3 holds 'space'
    li $t8,1 
    
    la $a0,msg
    li $v0,4
    syscall                        #$t8, is counter register
    
    li $v0,8                          #input of string para
    syscall
    
    li $t0,0                           # i=0
    
    loop:                    #till str[i]!=0
    add $t1,$a0,$t0
    
    lb $t2,0($t1)                   
    beq $t2,$zero,exit
    beq $t2,$t3,counter         #str[i]='  ' checks and jumps to 
    
    addi $t0,$t0,1                   #increment i if false
    j loop
    
    counter: addi $t8,$t8,1     #increment counter when word 
    
    addi $t0,$t0,1                  
    j loop
    
    exit: sw $t8,ctr
    li $v0,10
    syscall
    .end main