Golang : Turn string or text file into slice example
Alright, I need to parse a large number of text files that contain some raw data generated by a machine. Below is a small program that I've created to test how to write Golang program to turn string data or text file into a slice, delete one line base on the index/key position and insert a new line of string.
The delete and insert operations can be tricky, so care must be taken to ensure that the correct data are being manipulated.
This program below only handle embedded text string data. Please read the previous tutorial on how to read a text file and convert the data into lines of slice.
Here you go!
package main
import (
"fmt"
"strings"
)
func main() {
textString := `line 1
line 2
line 3
line 4`
lines := strings.Split(textString, "\n")
for i, line := range lines {
// i = i + 1 // uncomment to start from 1 instead of 0
fmt.Println(i, " : ", line)
}
// IMPORTANT: append() function will alter the lines slice
// therefore, let's make a copy of the original lines slice to preserve the data.
// Use make instead of var. If you use var, the destination slice will be empty!
originalLines := make([]string, len(lines))
copy(originalLines, lines[:])
// since lines is a slice, we can delete a line by index position
indexToDelete := 2 // remember counting starts from 0
linesAfterDelete := append(lines[:indexToDelete], lines[indexToDelete+1:]...)
fmt.Println("=======================================================")
// after delete
for i, line := range linesAfterDelete {
// i = i + 1 // uncomment to start from 1 instead of 0
fmt.Println(i, " : ", line)
}
fmt.Println("=======================================================")
fmt.Println("append() function will alter the lines slice, so make sure to keep a copy of the original slice")
fmt.Println("[lines] : ", lines)
fmt.Println("[original] : ", originalLines)
// we will use originalLines slice here instead of lines
fmt.Println("=======================================================")
indexToInsert := 1
stringToInsert := "Hello World!"
linesAfterInsert := append(originalLines[:indexToInsert], stringToInsert)
// don't forget to append the rest
linesAfterInsert = append(linesAfterInsert[:indexToInsert+1], originalLines[indexToInsert+1:]...)
// after insert
for i, line := range linesAfterInsert {
// i = i + 1 // uncomment to start from 1 instead of 0
fmt.Println(i, " : ", line)
}
}
Sample output:
0 : line 1
1 : line 2
2 : line 3
3 : line 4
=======================================================
0 : line 1
1 : line 2
2 : line 4
=======================================================
append() function will alter the lines slice, so make sure to keep a copy of the original slice
[lines] : [line 1 line 2 line 4 line 4]
[original] : [line 1 line 2 line 3 line 4]
=======================================================
0 : line 1
1 : Hello World!
2 : line 3
3 : line 4
Happy coding!
References:
See also : Golang : Display a text file line by line with line number example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.9k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+14.4k Golang : Convert(cast) int to float example
+18.2k Golang : Read binary file into memory
+26.6k Golang : Convert file content into array of bytes
+28.6k Golang : Detect (OS) Operating System
+25.1k Golang : Get current file path of a file or executable
+5.4k PHP : Fix Call to undefined function curl_init() error
+15.9k Golang : How to reverse elements order in map ?
+25.1k Golang : Convert uint value to string type
+8.3k Golang : Generate Datamatrix barcode
+11k Golang : Web routing/multiplex example
+16.9k Golang : XML to JSON example