Go String Manipulation and Type Conversion Basics
Lesson Overview
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.
Tokenizing a String in Go
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:
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.
Exploring String Concatenation
In Go, strings can be concatenated using the + operator:
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.
Trimming Whitespaces from Strings
In Go, you can use the strings.TrimSpace function to remove leading and trailing white spaces from a string:
In this example, strings.TrimSpace is used to remove all leading and trailing whitespaces from a string.
