Removing first and last empty lines from a string

I’ve the below text:

str := "
 

Maybe we should all just listen to
records and quit our jobs

— gach White —

AZ QUOTES

 

 

 "

And want to remove ALL empty lines.
I was able to remove the empty lines in the paragraphs as:

str = strings.Replace(str, "\n\n", "\n", -1)
fmt.Println(str)

And ended up with:

 
Maybe we should all just listen to
records and quit our jobs
— gach White —
AZ QUOTES




So, still have couple of empty lines at the beginning and few empty lines at the end, how can I get red of them?

In my app I’m trying to extract the texts from all “png” files in the same directory, and get it in pretty format, my full code so far is:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	_ "image/png"
)

func main() {
	var files []string

	root := "."
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if filepath.Ext(path) == ".png" {
			path = strings.TrimSuffix(path, filepath.Ext(path))
			files = append(files, path)
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
	for _, file := range files {
		fmt.Println(file)

		err = exec.Command(`tesseract`, file+".png", file).Run()
		if err != nil {
			fmt.Printf("Error: %s\n", err)
		} else {
			b, err := ioutil.ReadFile(file + ".txt") // just pass the file name
			if err != nil {
				fmt.Print(err)
			} else {
				str := string(b) // convert content to a 'string'
				str = strings.Replace(str, "\n\n", "\n", -1)
				fmt.Println(str) // print the content as a 'string'
			}
		}
	}

}

I found the solution as:

func trimEmptyLines(b []byte) string {
	strs := strings.Split(string(b), "\n")
	str := ""
	for _, s := range strs {
		if len(strings.TrimSpace(s)) == 0 {
			continue
		}
		str += s + "\n"
	}
	str = strings.TrimSuffix(str, "\n")

	return str
}

And calling it as:

str := trimEmptyLines(b)

You can just use trimspace fn to remove lines.

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := `


	Maybe we should all just listen to
	records and quit our jobs

	— gach White —

	AZ QUOTES





	`
	fmt.Println(strings.TrimSpace(str))

}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.