Go String Manipulation
When working with a string of characters, Go has a number of built in functions that allow for them to be easily manipulated. These reside in the 'fmt' and 'strings' packages.
When working with the console, a string can be displayed using either the 'Print' or ‘Println’ function.
fmt.Print("Hello world!\n")
fmt.Println("Hello world!")
The difference between the two functions is that 'Print' doesn't include a new line character at the end, whereas 'Println' does. In the above example a new line is added when using the 'Print' function by including the new line escape character, '\n'.
If it is necessary to incorporate the value of a variable into this message it can be done in a couple of different ways, using either the 'Print', 'Println' or 'Printf' functions.
var fname string = "Bob" fmt.Print("Hello " + fname + "!\n") fmt.Println("Hello " + fname + "!") fmt.Printf("Hello %s!\n", fname)
All three of the above examples display the same message in the console, ‘Hello Bob!’. The first two examples use the ‘+’ symbol to concatenate the variable into the string. The last example uses the string format specifier, '%s', to incorporate the variable into the string. Format specifiers act as a placeholder for a variable of a particular type, in this case string. The function 'Printf', like 'Print', doesn't include a new line character at the end.
Below are some other examples of formatted strings incorporating a Boolean, integer and float variable.
var exampleBoolean1 bool = true var exampleInt1 int = 5 var exampleFloat1 float32 = 5.4 fmt.Printf("Boolean: %t\n", exampleBoolean1) fmt.Printf("Integer: %d\n", exampleInt1) fmt.Printf("Float: %g\n", exampleFloat1)
These examples produce the following output.
Boolean: true Integer: 5 Float: 5.4
Two variables can be incorporated by separating them with a comma.
var fname string = "Bob" var age int = 30 fmt.Printf("%s is %d years old.\n", fname, age)
The output from the above is shown below.
Bob is 30 years old.
Index Value
Every character in a string has an index value, which can be used to reference it. The first character has an index value of zero, the second has an index of one and so on.
var example string = "This is a string." fmt.Printf("%c\n", example[3])
Here, the index value of three in square brackets is used to output the fourth character of the string, using the character format specifier, '%c'.
It is also possible to find the index position of a character in a string using the ‘Index’ function of the 'strings' package.
fmt.Printf("%d\n", strings.Index(example, "i"))
Note that, the ‘Index’ function will return the index position of the first occurrence of a character, if more than one exists in the string. If the character doesn't exist in the string at all then '-1' will be returned.
Substring
The index values of a string can be used to return a portion of a string. Here, a start index position of ten and an end index position of sixteen is used to return the word ‘string’ from the variable.
var example string = "This is a string." fmt.Printf("%s\n", example[10:16])
This is known as a ‘slice’.
Upper and Lower Case
In order to change a string to upper or lower case, there are two functions that can be used, ‘ToUpper’ and ‘ToLower’.
var example string = "This is a string." fmt.Println(strings.ToUpper(example)) fmt.Println(strings.ToLower(example))
The first will change the whole string to upper case and the latter will convert it to lower case.
THIS IS A STRING. this is a string.
Trim
If a string has extra spacing at the start, end, or both, it’s possible to remove this using the ‘TrimSpace’ function as demonstrated below.
var example string = " This is a string. " fmt.Printf("%s\n", strings.TrimSpace(example))
As well as being able to remove spaces, it is also possible to remove specified characters. Here, both '*' and '-' are removed from the start and end of the string. It is also possible just to remove these characters from the start or end using the 'TrimLeft' or 'TrimRight' functions.
var example string = "*-*This is a string.*-*" fmt.Printf("%s\n", strings.Trim(example, "*-")) fmt.Printf("%s\n", strings.TrimLeft(example, "*-")) fmt.Printf("%s\n", strings.TrimRight(example, "*-"))
This produces the following output.
This is a string. This is a string.*-* *-*This is a string.
If it is necessary to remove a prefix or suffix from a string, then this can be achieved using the 'TrimPrefix' and 'TrimSuffix' functions.
var example string = "Prefix - This is a string. - Suffix" fmt.Printf("%s\n", strings.Trim(example, "*-")) fmt.Printf("%s\n", strings.TrimPrefix(example, "Prefix - ")) fmt.Printf("%s\n", strings.TrimSuffix(example, " - Suffix"))
The result can be seen below.
Prefix - This is a string. - Suffix This is a string. - Suffix Prefix - This is a string.
Length
Sometimes it is necessary to find the size or length of a string. This can be done using the ‘len’ function.
var example string = "This is a string." fmt.Printf("%d\n", len(example))
Replace
The ‘Replace’ function can be used to replace a specified part of a string with some other text.
var example string = "This is a string." fmt.Printf("%s\n", strings.Replace(example, " is", " was", 1))
Here, the function is used to replace ' is' with ' was' in the variable 'example'. The last argument, '1', means replace the first instance of ' is' in the string only. Specifying two here would replace the first two instances, and so on. Including a '-1' would replace all instances of the desired text.