如何在Golang中找到字符索引? [英] How to find a character index in Golang?

查看:462
本文介绍了如何在Golang中找到字符索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Go中查找 @字符串字符,但找不到解决方法。我知道如何索引像 HELLO [1]这样的字符,它将输出 E。但是,我试图找到所找到字符的索引号。

I'm trying to find "@" string character in Go but I cannot find a way to do it. I know how to index characters like "HELLO[1]" which would output "E". However I'm trying to find index number of the found char.

在Python中,我可以通过以下方式进行操作:

In Python I'd do it in following way:

x = "chars@arefun"
split = x.find("@")
chars = x[:split]
arefun = x[split+1:]

>>>print split
5
>>>print chars
chars
>>>print arefun
arefun

所以chars将返回 chars并且当使用 @定界符时,arefun将返回 arefun。我一直在努力寻找解决方法达数小时之久,但似乎找不到在Golang中解决问题的正确方法。

So chars would return "chars" and arefun would return "arefun" while using "@" delimeter. I've been trying to find solution for hours and I cannot seem to find proper way to do it in Golang.

推荐答案

您可以使用包 strings 索引函数>

You can use the Index function of package strings

游乐场: https://play.golang .org / p / _WaIKDWCec

package main

import "fmt"
import "strings"

func main() {
    x := "chars@arefun"

    i := strings.Index(x, "@")
    fmt.Println("Index: ", i)
    if i > -1 {
        chars := x[:i]
        arefun := x[i+1:]
        fmt.Println(chars)
        fmt.Println(arefun)
    } else {
        fmt.Println("Index not found")
        fmt.Println(x)
    }
}

这篇关于如何在Golang中找到字符索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆