英文:
How can I check the first character of a scanned string even if it is empty?
问题
我想让用户能够输入内容,并检查第一个字符是否为a
,但如果他们将字符串留空,则会出现以下错误:
panic: runtime error: index out of range [0] with length 0
我的代码如下:
package main
import "fmt"
func main() {
var a string;
fmt.Scanln(&a);
if string(a[0]) == "a" {
fmt.Println("if true");
}
}
英文:
I want to have the user be able to put in input and check to see if the first character is an a
but if they leave the string empty then it will cause the following error:
panic: runtime error: index out of range [0] with length 0
My code looks like:
package main
import "fmt"
func main() {
var a string;
fmt.Scanln(&a);
if string(a[0]) == "a" {
fmt.Println("if true");
}
}
答案1
得分: 3
一种方法是只检查第一个字符是否为"a"
var a string
fmt.Scanln(&a)
if len(a) > 0 && string(a[0]) == "a" {
fmt.Println("if true")
}
另一种方法可以处理前导空格,例如当Scanln
的输入为" a"
时:
var a string
fmt.Scanln(&a)
if strings.HasPrefix(a, "a") {
fmt.Println("if true")
}
英文:
One way to do it, will only check if the first character is "a"
var a string;
fmt.Scanln(&a);
if len(a) > 0 && string(a[0]) == "a" {
fmt.Println("if true")
}
Another, will work with leading spaces, for example when the input to Scanln
is " a"
:
var a string;
fmt.Scanln(&a);
if strings.HasPrefix(a, "a") {
fmt.Println("if true")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论