简体   繁体   English

如何检查Go中字符串的第一个字符,即使它是空白的?

[英]How Can I Check The First Character of A String in Go Even If It Is Blank?

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 an error that outputs我希望用户能够输入并检查第一个字符是否为“a”,但如果他们将字符串留空,则会导致输出错误

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

One way to do it, will only check if the first character is "a"一种方法,只检查第一个字符是否为"a"

if len(a) > 0 && string(a[0]) == "a" {
    fmt.Println("if true")
}

Another, will work with leading spaces, for example " a"另一个,将使用前导空格,例如" a"

if strings.HasPrefix(a, “a”) {
    fmt.Println("if true")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM