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.
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) } }
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.
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