"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 do you find the index of a specific character in a Go string?

How do you find the index of a specific character in a Go string?

Published on 2024-11-11
Browse:701

How do you find the index of a specific character in a Go string?

Finding Character Index in Go

Your requirement is to locate the index of a specific character in a string using Golang. While you can access a character by index using the string indexing notation, determining the index of a particular character can be cumbersome.

Solution using the Index Function

To address this issue, Go provides the Index function found in the strings package. This function returns the index of the first occurrence of a substring within a string. For your case, you're searching for the "@" character.

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: ", chars)
        fmt.Println("Arefun: ", arefun)
    } else {
        fmt.Println("Character '@' not found")
        fmt.Println(x)
    }
}

Demonstration

In the code above, we create a string variable x containing the sample text "chars@arefun." We then use the Index function to locate the index of the "@" character, which is stored in variable i.

If the index i is not negative, it indicates that the character was found. We proceed to split the string into two parts: the part before the "@" character (assigned to the variable chars) and the part after the "@" character (assigned to the variable arefun).

Finally, we print the values of both chars and arefun to demonstrate the successful retrieval of the character index and the resulting substrings.

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