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
+8.3k Golang : Convert word to its plural form example
+5.4k Golang : Get S3 or CloudFront object or file information
+14k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+18.5k Golang : Send email with attachment
+18.3k Golang : How to get hour, minute, second from time?
+9.3k Golang : Terminate-stay-resident or daemonize your program?
+7.5k Android Studio : AlertDialog to get user attention example
+10.5k Golang : Select region of interest with mouse click and crop from image
+9.6k Random number generation with crypto/rand in Go
+7.2k Golang : alternative to os.Exit() function