string 访问字符串中的一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7590310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing one character in a string
提问by darksky
I am using something like SPIMS or MARS with syscall functions.
我正在使用带有系统调用函数的 SPIMS 或 MARS 之类的东西。
I am reading in a string (and it works because I can print it out) as follows:
我正在读取一个字符串(它有效,因为我可以打印出来)如下:
li $v0, 8
la $a0, string
li $a1, 256
syscall
However, I am having a problem accessing a single character of the string. So if I want to access the first character and print it, I am trying this:
但是,我在访问字符串的单个字符时遇到问题。所以如果我想访问第一个字符并打印它,我正在尝试这个:
la $t0, string
lb $a0, ($t0)
li $v0, 4
sys call
If I try something like this:
如果我尝试这样的事情:
la $a0, string
li $v0, 4
syscall
This prints out the whole string as string points to the whole string.
这将打印出整个字符串,因为字符串指向整个字符串。
If I try something like:
如果我尝试类似的事情:
la $a0, string
lb $a0, ($t0)
li $v0, 4
syscall
It gives me an out of bound error. I don't understand why though - isn't a character a byte long and this just loads the first byte from the string into $a0?
它给了我一个越界错误。我不明白为什么 - 不是一个字节长的字符,这只是将字符串中的第一个字节加载到 $a0 中?
Thank you
谢谢
回答by user786653
Looking at the documentationfor the MARS syscall functions you can see that service 4, which you're using, expects $a0
to be "[the] address of null-terminated string to print", which explains the behavior you're seeing.
查看MARS 系统调用函数的文档,您可以看到您正在使用的服务 4 期望$a0
是“要打印的空终止字符串的 [the] 地址”,这解释了您所看到的行为。
What you want is function 11 "print character", which prints the low-order byte as a character. In other words the following should work (not tested):
您想要的是功能 11“打印字符”,它将低位字节打印为字符。换句话说,以下应该工作(未测试):
la $t0, string
lb $a0, ($t0)
li $v0, 11
syscall