Home  >  Article  >  Backend Development  >  How to Remove Newlines from Line Outputs in Go?

How to Remove Newlines from Line Outputs in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 18:28:03978browse

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:

  • Slicing: You can slice off the last character from the read line using:
read_line = read_line[:len(read_line)-1]
  • strings.TrimSuffix: Alternatively, you can use the strings library to trim the newline character:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn