Strings in Golang
Lesson 12 of 19 in Coddy's Functions and Pointers in Golang course.
Strings in Go are just sequences of characters, and we can perform almost all operations that we can do with an array. We can slice them into different chunks, get their length, and so on.
Let's consider a string like this:
var name = "Coddy"Similar to slices and arrays, we can get the length using the len() function:
fmt.Println(len(name))The result will be:
5To access a specific character based on the index:
var name = "Coddy"
fmt.Println(name[0])Just like arrays and slices, indexing starts from 0. Running this will get:
9999 is the Unicode value of the character C. To get the character value, we need to convert the Unicode value to a string using the string() function:
var name = "Coddy"
fmt.Println(string(name[0]))As a result, we will get the character "C".
We can also slice strings into different chunks like this:
var name = "Coddy"
fmt.Println(name[1:4])The result will be:
oddHere, we get the string value "odd" without having to explicitly convert it to a string. In Go, if we access a single specific value using the index, we get the Unicode value, which we call a rune, another data type in Go.
Challenge
EasyWrite a function called printCharacters that takes a string value.
- Print the length of the string.
- Iterate over the string value and print the index and the character. For example:
Input string: "Coddy"
Output:
0 C
1 o
2 d
3 d
4 yTry it yourself
import "fmt"
// Write Your Function Here
All lessons in Functions and Pointers in Golang
1Introduction
Introduction4Rebuild Go Strings Functions
Strings in GolangJoin FunctionContains FunctionIndex FunctionRecap Challenge #1