search

Explain the use of Go's string functions for string manipulation and processing?

Go provides a variety of built-in string functions for string manipulation and processing. Here are some examples:

**len()** - This function returns the length of a string in bytes.

str := "hello"
length := len(str) // length = 5

**strings.ToUpper()** - This function returns a new string with all characters in uppercase.

str := "hello"
newStr := strings.ToUpper(str) // newStr = "HELLO"

**strings.ToLower()** - This function returns a new string with all characters in lowercase.

str := "HELLO"
newStr := strings.ToLower(str) // newStr = "hello"

**strings.TrimSpace()** - This function returns a new string with leading and trailing white space removed.

str := "   hello   "
newStr := strings.TrimSpace(str) // newStr = "hello"

**strings.Split()** - This function splits a string into a slice of substrings based on a delimiter.

str := "hello,world"
substrings := strings.Split(str, ",") // substrings = []string{"hello", "world"}

**strings.Join()** - This function concatenates a slice of strings into a single string with a specified separator.

substrings := []string{"hello", "world"}
str := strings.Join(substrings, ",") // str = "hello,world"

**strconv.Itoa()** - This function converts an integer to a string. 

num := 42
str := strconv.Itoa(num) // str = "42"

**strconv.Atoi()** - This function converts a string to an integer.

str := "42"
num, err := strconv.Atoi(str) // num = 42, err = nil

These are just a few examples of the many string functions available in Go. By using these functions, you can easily manipulate and process string data in your programs.

Related Questions You Might Be Interested