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
+11k CodeIgniter : How to check if a session exist in PHP?
+11.9k Golang : Pagination with go-paginator configuration example
+5.9k Golang : Extract XML attribute data with attr field tag example
+36.4k Golang : Display float in 2 decimal points and rounding up or down
+6.7k Golang : Normalize email to prevent multiple signups example
+12.7k Python : Convert IPv6 address to decimal and back to IPv6
+12.8k Swift : Convert (cast) Int to String ?
+7.6k Golang : Reverse a string with unicode
+9.9k Golang : Get login name from environment and prompt for password
+48.3k Golang : Upload file from web browser to server
+16.3k Golang : File path independent of Operating System