I'm reading file line by line and like to split line based on substring. But when I use SplitAfterN with read line passed, I'm facing below error,
cannot convert 'variable' (type []string) to type string
where 'variable' = []string type
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"strings"
)
func main() {
var fLine []string
FileName := flag.String("fpath", "Default file path", "File path description ")
flag.Parse()
fptr, err := os.Open(*FileName)
if err != nil {
log.Fatal(err)
}
FileScanner := bufio.NewScanner(fptr)
for FileScanner.Scan() {
// Append each line into one buffer while reading
fLine = append(fLine, FileScanner.Text())
splitline := strings.SplitAfterN(fLine, "12345", 2)
fmt.Println("Splited string = ", splitline[1])
}
}
I'm expecting below line to split passed argument (fLine) splitline := strings.SplitAfterN(fread, "12345", 2)
The (last) line you read is not fLine
, that is a slice of all lines. The last line is returned by FileScanner.Text()
. If you want to split the last line, either store that in a variable, or use the last element of the slice.
If you choose to store it in a variable:
line := FileScanner.Text()
fLine = append(fLine, line)
splitline := strings.SplitAfterN(line, "12345", 2)
If you just want to use the last slice element:
fLine = append(fLine, FileScanner.Text())
splitline := strings.SplitAfterN(fLine[len(fLine)-1], "12345", 2)
So you just want to convert the slice to a string, right?
This should do what you need..
So:
splitline := strings.SplitAfterN(strings.Join(fLine," "), "12345", 2)