- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to split a string in Golang?
Splitting a string means being able to get a part of a string, and that part can either be based on a position or a character in the string.
In Go, if we want to split a string on the basis of positions, we can make use of the [ ] (square brackets) and then pass the indices in them separated by a colon.
Syntax
Consider the syntax shown below.
sl[startingIndex : EndingIndex]
It should be noted that the element at the EndingIndex in the slice won't be considered, as the range is from startingIndex to (EndingIndex−1).
Example 1
Now, let's consider an example where we will split a string on the basis of different positions.
Consider the code shown below.
package main import ( "fmt" ) func main() { var secretString string = "this is a top secret string" res := secretString[0:10] res2 := secretString[:5] res3 := secretString[10:] fmt.Println(res, res2, res3) }
Output
If we run the command go run main.go in the above code, then we will get the following output in the terminal.
this is a this top secret string
Example 2
We can also split the string in Go on the basis of a particular character. Consider the code shown below.
package main import ( "fmt" "reflect" "strings" ) func main() { var secretString string = "this is not a top secret string" res := strings.Split(secretString, "n") checkType := reflect.TypeOf(res) fmt.Println(res) fmt.Println(checkType) }
In the above example, we are splitting the string on the basis of character "n". It will result in a slice where there will be two values inside it, the first will contain all the characters that occurred before the character 'n' and then all the ones after it.
Output
If we run the command go run main.go in the above code, then we will get the following output in the terminal.
[this is ot a top secret stri g] []string
- Related Articles
- How to split a string in Java?
- How to split a string in Python
- How to split string by a delimiter string in Python?
- How to split a string with a string delimiter in C#?
- How to split a string in Lua programming?
- How to Split Text Using Regex in Golang?
- How to split a string into elements of a string array in C#?
- How to Split a String with Escaped Delimiters?
- How to split a string using regular expressions in C#?
- How to split a String into an array in Kotlin?
- How to print a string in Golang?
- How to Trim a String in Golang?
- How to split string on whitespace in Python?
- How to split string in MySQL using SUBSTRING_INDEX?
- Split a string in Java
