Go by Example: String Functions

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 string
  • concatenation: the + operator can be used to concatenate two strings
  • substring: the [start:end] syntax can be used to extract a substring from a string
  • contains: the strings.Contains function returns true if a string contains a specified substring
  • index: the strings.Index function returns the first index of a specified substring in a string
  • replace: the strings.Replace function replaces all occurrences of a specified substring with another string
  • split: the strings.Split function splits a string into a slice of substrings based on a specified delimiter
  • join: the strings.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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *