Home > Article > Backend Development > How to Remove Newlines from Line Outputs in Go?
Eliminating Newlines in Line Outputs
In the following code snippet, a newline (n) character is inadvertently being appended to the end of each line:
file, _ := os.Open("x.txt") f := bufio.NewReader(file) for { read_line, _ := ReadString('\n') fmt.Print(read_line) // Other code that operates on the parsed line... }
As a result, the code processes and prints each line correctly, but also appends an unnecessary newline at the end. To remedy this issue, we need to remove the newline character from the line before printing it.
Solution
There are several ways to accomplish this:
read_line = read_line[:len(read_line)-1]
read_line = strings.TrimSuffix(read_line, "\n")
Example:
Here is a revised version of the code that correctly trims off the newline character:
file, _ := os.Open("x.txt") f := bufio.NewReader(file) for { read_line, _ := f.ReadString('\n') read_line = read_line[:len(read_line)-1] // Slice off the last character fmt.Print(read_line) // Other code that operates on the parsed line... }
With this modification, the code will now process and print each line of the file without the unintended newline character.
The above is the detailed content of How to Remove Newlines from Line Outputs in Go?. For more information, please follow other related articles on the PHP Chinese website!