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

Patricia Arquette
Release: 2024-11-11 12:44:03
Original
714 people have browsed it

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")
    }
}
Copy after login

Output:

Index: 5
chars: chars
arefun: arefun
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template