Source From Here
Preface
In the example below we are looking at how to take the first x number of characters from the start of a string. If we know a character we want to separate on, like a space, we can use strings.Split() instead. But for this we’re looking to get the first 6 characters as a new string.
HowTo
To do this we first convert it into a rune, allowing for better support in different languages and allowing us to use it like an array. Then we pick the first characters using [0:6] and converting it back to a string.
Split Based on Position:
Output:
Split Based on Character:
The alternative way, using the strings package would be:
Output:
Supplement
* The Go Blog - Strings, bytes, runes and characters in Go
In the example below we are looking at how to take the first x number of characters from the start of a string. If we know a character we want to separate on, like a space, we can use strings.Split() instead. But for this we’re looking to get the first 6 characters as a new string.
HowTo
To do this we first convert it into a rune, allowing for better support in different languages and allowing us to use it like an array. Then we pick the first characters using [0:6] and converting it back to a string.
Split Based on Position:
- package main
- import (
- "fmt"
- )
- func main() {
- myString := "Hello! This is a golangcode.com test ;)"
- // Step 1: Convert it to a rune
- a := []rune(myString)
- // Step 2: Grab the num of chars you need
- myShortString := string(a[0:6])
- fmt.Println(myShortString)
- }
Split Based on Character:
The alternative way, using the strings package would be:
- package main
- import (
- "fmt"
- "strings"
- )
- func main() {
- myString := "Hello! This is a golangcode.com test ;)"
- strParts := strings.Split(myString, "!")
- fmt.Println(strParts[0])
- }
Supplement
* The Go Blog - Strings, bytes, runes and characters in Go
沒有留言:
張貼留言