"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find the Index of a Character in a Go String?

How to Find the Index of a Character in a Go String?

Posted on 2025-03-05
Browse:199

How to Find the Index of a Character in a Go String?

Finding Character Index in Go with Strings Package

You can retrieve the index of a character in a string using the Index function from the strings package.

Example Usage:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "chars@arefun"
    char := "@"

    // Find the index of the character using strings.Index
    index := strings.Index(str, char)

    if index != -1 {
        // If the character was found, split the string based on the index
        chars := str[:index]
        arefun := str[index 1:]

        fmt.Println("Index:", index)
        fmt.Println("chars:", chars)
        fmt.Println("arefun:", arefun)
    } else {
        fmt.Println("Character not found")
    }
}

Output:

Index: 5
chars: chars
arefun: arefun
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3