Skip to content

Instantly share code, notes, and snippets.

@adria0
Last active June 19, 2017 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adria0/a45fc7def084440ae3b196091f4356db to your computer and use it in GitHub Desktop.
Save adria0/a45fc7def084440ae3b196091f4356db to your computer and use it in GitHub Desktop.
format and center align text
package main
import (
"fmt"
"strings"
)
func cutncenter(text string, ncol int) string {
align := func (linewords []string, ncol int) string {
length := 0
for _,w := range(linewords) {
length = length + len(w)
}
var inc float64 = 0.0
if len(linewords) > 1 {
inc = float64(ncol-length+0.0) / float64(len(linewords)-1)
}
line := linewords[0]
for i:=1;i<len(linewords);i++ {
diff := int(float64(i)*inc)-int(float64(i-1)*inc)
space := strings.Repeat(" ",int(diff))
line = line + space + linewords[i]
}
return line
}
ret := ""
words := strings.Split(text," ")
length := 0
linewords := []string{}
for _,word := range(words) {
if len(words) > 0 {
length++
}
linewords = append(linewords,word)
length += len(word)
if length>ncol {
ret += align(linewords[:len(linewords)-1],ncol)+"\n"
length = len(word)
linewords = []string{word}
}
}
ret += align(linewords,ncol)
return ret
}
func main() {
text := "Lorem Ipsum xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx es es simplementeel texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estandar"
fmt.Println(strings.Repeat("-",30))
fmt.Println(cutncenter(text,30))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment