Welcome! In this lesson, we'll delve into the basic string manipulation features of Go, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.
In Go, you can split a string into smaller parts, or tokens, using the strings.Split
function from the strings
package. Here's an example:
Go1package main 2 3import ( 4 "fmt" 5 "strings" 6) 7 8func main() { 9 sentence := "Go is an amazing language!" 10 tokens := strings.Split(sentence, " ") 11 12 for _, token := range tokens { 13 fmt.Println(token) 14 } 15 // Output: 16 // Go 17 // is 18 // an 19 // amazing 20 // language! 21}
In the example above, we use a space as a delimiter to split the sentence
into individual words with strings.Split(sentence, " ")
. Then, the for loop prints each word in the sentence on a new line.
In Go, strings can be concatenated using the +
operator:
Go1package main 2 3import ( 4 "fmt" 5 "strings" 6) 7 8func main() { 9 str1 := "Hello," 10 str2 := " World!" 11 greeting := str1 + str2 12 fmt.Println(greeting) // Output: "Hello, World!" 13 14 str3 := " Go is fun." 15 greeting += str3 16 fmt.Println(greeting) // Output: "Hello, World! Go is fun." 17 18 words := []string{"Go", "is", "an", "amazing", "language"} 19 sentence := strings.Join(words, " ") 20 fmt.Println(sentence) // Output: "Go is an amazing language" 21}
In this example, we use the +
operator to construct a larger string from smaller strings. The +=
operator appends a string to the existing string, effectively creating a new string with the original content and the appended string. Recall that in Go strings are immutable, so both +
and +=
result in the creation of a new string rather than modifying the original(s).
Additionally, we use the strings.Join
function to concatenate elements from a slice of strings (words
) into a single string (sentence
). Here, a space is used as a separator between each word. This approach is efficient when concatenating multiple strings as it avoids creating multiple intermediate strings.
In Go, you can use the strings.TrimSpace
function to remove leading and trailing white spaces from a string:
Go1package main 2 3import ( 4 "fmt" 5 "strings" 6) 7 8func main() { 9 str := " Hello, World! " // string with leading and trailing spaces 10 str = strings.TrimSpace(str) 11 fmt.Println(str) // Output: "Hello, World!" 12}
In this example, strings.TrimSpace
is used to remove all leading and trailing whitespaces from a string.
You can convert strings to numbers using functions from the strconv
package like strconv.Atoi
for integers and strconv.ParseFloat
for floats. Conversely, you can convert numbers to strings using strconv.Itoa
or fmt.Sprintf
:
Go1package main 2 3import ( 4 "fmt" 5 "strconv" 6) 7 8func main() { 9 numStr := "123" 10 num, _ := strconv.Atoi(numStr) 11 fmt.Println(num) // Output: 123 12 13 floatStr := "3.14" 14 pi, _ := strconv.ParseFloat(floatStr, 64) 15 fmt.Println(pi) // Output: 3.14 16 17 age := 20 18 ageStr := strconv.Itoa(age) 19 fmt.Println("I am " + ageStr + " years old.") // Output: I am 20 years old. 20 21 height := 1.75 22 heightStr := fmt.Sprintf("%.2f", height) 23 fmt.Println("My height is " + heightStr) // Output: My height is 1.75 24}
In this code, we use strconv.Atoi
, strconv.ParseFloat
, and strconv.Itoa
for type conversions. Moreover, we use fmt.Sprintf
to format a float (height
) as a string with two decimal places by specifying "%.2f"
.
In Go, your own functions can be created to organize code and reuse logic. A function has a name, parameters (optional), return types, and a body. Here's a basic structure:
Go1package main 2 3import "fmt" 4 5func greet(name string) string { 6 return "Hello, " + name 7} 8 9func main() { 10 fmt.Println(greet("Alice")) // Output: Hello, Alice 11}
In this example, greet
is a function that takes a string parameter name
and returns a string. The function concatenates the string "Hello, " with the value passed to the name
parameter.
Now that we know how to define functions, let's integrate all string operations discussed today into a function:
Go1package main 2 3import ( 4 "fmt" 5 "strconv" 6 "strings" 7) 8 9func calculateAverage(numbers string) float64 { 10 numStrings := strings.Split(numbers, ",") 11 sum := 0 12 for _, numStr := range numStrings { 13 num, _ := strconv.Atoi(numStr) 14 sum += num 15 } 16 average := float64(sum) / float64(len(numStrings)) 17 return average 18} 19 20func main() { 21 numbers := "1,2,3,4,6" 22 average := calculateAverage(numbers) 23 fmt.Printf("The average is %.2f\n", average) // Output: The average is 3.20 24}
By integrating these methods within the calculateAverage
function:
- We split the string
"1,2,3,4,6"
into individual digit characters withstrings.Split(numbers, ",")
; - We loop over each digit, converting to an integer using
strconv.Atoi
and summing them up; - Finally, we calculate the average and return the result.
Great job! You've gained an overview of Go's string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, type conversions, and an introduction to user-created functions. Now, it's time to get hands-on with these concepts in the exercises that follow. Happy coding!