2020年10月13日 星期二

[ 常見問題 ] Substring: How to Split a String

 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:
  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5. )  
  6.   
  7. func main() {  
  8.   
  9.     myString := "Hello! This is a golangcode.com test ;)"  
  10.   
  11.     // Step 1: Convert it to a rune  
  12.     a := []rune(myString)  
  13.   
  14.     // Step 2: Grab the num of chars you need  
  15.     myShortString := string(a[0:6])  
  16.   
  17.     fmt.Println(myShortString)  
  18. }  
Output:
Hello!

Split Based on Character:
The alternative way, using the strings package would be:
  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5.     "strings"  
  6. )  
  7.   
  8. func main() {  
  9.   
  10.     myString := "Hello! This is a golangcode.com test ;)"  
  11.   
  12.     strParts := strings.Split(myString, "!")  
  13.   
  14.     fmt.Println(strParts[0])  
  15. }  
Output:
Hello

Supplement
The Go Blog - Strings, bytes, runes and characters in Go
The Go language defines the word rune as an alias for the type int32, so programs can be clear when an integer value represents a code point. Moreover, what you might think of as a character constant is called a rune constant in Go...


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...