String is a data type in Go language and represents a slice of bytes that are ""
. These strings are read-only and their values cannot be changed once defined.
Below is a simple example of how strings are defined and printed in Go:
package mainimport "fmt"func main() {str := "Hello World" //define stringfmt.Println(str) // print string}
The following table contains a list of escape sequences when a string is enclosed in double-quotes:
Escape sequence | Purpose |
\' | Single quote |
\" | Double quote |
\n | New line |
\t | Horizontal tab |
\v | Vertical tab |
\001 | A 3-digit code that represents an 8-bit unicode character |
\b | Backspace |
\a | An alert or bell sound |
\r | Return to start of the line (carriage feed) |
\f | Go to the next page (form feed) |
\xhh | Byte where h= hexadecimal digit |
\uhhhh or \Uhhhhhhhh | Unicode character of either 4 or 8 hexadecimal digits respectively |
The length of a string can be found by using the len()
function in Go language. Below is an example that highlights how one can check the length of a string:
package mainimport "fmt"/* For exercises uncomment the imports below */// import "strconv"// import "encoding/json"func main() {str := "Hello world!"length := len(str)fmt.Println("The length of the string is", length)}
You can iterate over a string by using a loop that accesses each character as well as the index of a string. Below is an example that demonstrates how you can loop over a string:
package mainimport "fmt"/* For exercises uncomment the imports below */// import "strconv"// import "encoding/json"func main() {str := "Hello world!"for index,character := range str {fmt.Printf("Character: %c Index %d\n", character, index)}}