如何在扫描的字符串中检查第一个字符,即使它是空的?

huangapple go评论86阅读模式
英文:

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")
}

huangapple
  • 本文由 发表于 2021年12月20日 07:59:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/70416221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定