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

DDD
Release: 2024-11-12 18:06:02
Original
744 people have browsed it

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

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.

The above is the detailed content of How do you find the index of a specific 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template