Home >Backend Development >Golang >How to Find the Index of a Character in a Go String?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 12:44:03785browse

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

The above is the detailed content of How to Find the Index of a Character in a Go String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn