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

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

How can I check the first character of a scanned string even if it is empty?

问题

我想让用户能够输入内容,并检查第一个字符是否为a,但如果他们将字符串留空,则会出现以下错误:

  1. panic: runtime error: index out of range [0] with length 0

我的代码如下:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var a string;
  5. fmt.Scanln(&a);
  6. if string(a[0]) == "a" {
  7. fmt.Println("if true");
  8. }
  9. }
英文:

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:

  1. panic: runtime error: index out of range [0] with length 0

My code looks like:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var a string;
  5. fmt.Scanln(&a);
  6. if string(a[0]) == "a" {
  7. fmt.Println("if true");
  8. }
  9. }

答案1

得分: 3

一种方法是只检查第一个字符是否为"a"

  1. var a string
  2. fmt.Scanln(&a)
  3. if len(a) > 0 && string(a[0]) == "a" {
  4. fmt.Println("if true")
  5. }

另一种方法可以处理前导空格,例如当Scanln的输入为" a"时:

  1. var a string
  2. fmt.Scanln(&a)
  3. if strings.HasPrefix(a, "a") {
  4. fmt.Println("if true")
  5. }
英文:

One way to do it, will only check if the first character is "a"

  1. var a string;
  2. fmt.Scanln(&a);
  3. if len(a) > 0 && string(a[0]) == "a" {
  4. fmt.Println("if true")
  5. }

Another, will work with leading spaces, for example when the input to Scanln is " a":

  1. var a string;
  2. fmt.Scanln(&a);
  3. if strings.HasPrefix(a, "a") {
  4. fmt.Println("if true")
  5. }

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:

确定