Go provides a variety of built-in string functions that make it easy to manipulate and process strings. Here are some common string functions in Go:
len
: returns the length of a stringconcatenation
: the+
operator can be used to concatenate two stringssubstring
: the[start:end]
syntax can be used to extract a substring from a stringcontains
: thestrings.Contains
function returnstrue
if a string contains a specified substringindex
: thestrings.Index
function returns the first index of a specified substring in a stringreplace
: thestrings.Replace
function replaces all occurrences of a specified substring with another stringsplit
: thestrings.Split
function splits a string into a slice of substrings based on a specified delimiterjoin
: thestrings.Join
function joins a slice of strings into a single string using a specified delimiter
Here’s an example of using some of these string functions:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
fmt.Println("Length:", len(str))
newStr := "Hello" + ", " + "Go"
fmt.Println("Concatenated:", newStr)
sub := str[7:12]
fmt.Println("Substring:", sub)
fmt.Println("Contains 'Hello':", strings.Contains(str, "Hello"))
fmt.Println("Index of 'World':", strings.Index(str, "World"))
newStr = strings.Replace(str, "World", "Go", 1)
fmt.Println("Replaced:", newStr)
parts := strings.Split(str, " ")
fmt.Println("Split:", parts)
newStr = strings.Join(parts, "-")
fmt.Println("Joined:", newStr)
}
In this example, the str
variable is assigned the string value "Hello, World!"
. The len
function is used to print the length of the string, and the +
operator is used to concatenate two strings to form a new string. The [start:end]
syntax is used to extract a substring from the str
variable, and the strings.Contains
function is used to check if the string contains a specified substring. The strings.Index
function is used to find the first index of a specified substring, and the strings.Replace
function is used to replace all occurrences of a specified substring with another string. The strings.Split
function is used to split the string into a slice of substrings based on a specified delimiter, and the strings.Join
function is used to join the slice of strings into a single string using a specified delimiter.
Leave a Reply