Skip to content

Instantly share code, notes, and snippets.

@CyrusRoshan
Last active October 26, 2017 20:05
Show Gist options
  • Save CyrusRoshan/f2c8cf081b89e5e3faac9220b8bf2b86 to your computer and use it in GitHub Desktop.
Save CyrusRoshan/f2c8cf081b89e5e3faac9220b8bf2b86 to your computer and use it in GitHub Desktop.
Some simple string formatting
// Input:
// go run stringformat.go "testing this"
// Output:
// **************
// *TeStInG ThIs*
// *EsTiNg tHiS *
// *StInG ThIs *
// *TiNg tHiS *
// *InG ThIs *
// *Ng tHiS *
// *G ThIs *
// * tHiS *
// *ThIs *
// *HiS *
// *Is *
// *S *
// **************
package main
import (
"bytes"
"fmt"
"os"
"strings"
"unicode"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please add the string to fill, as a cli argument")
return
}
spicedStr := formatString(os.Args[1])
fmt.Println(spicedStr)
}
func formatString(str string) string {
lowercaseStr := strings.ToLower(str)
stringBox := crossFillArr(lowercaseStr)
alternatedBox := alternateCapsBoxFill(stringBox)
spacedBox := spaceNullBoxChars(alternatedBox)
boundedBox := boundBox(spacedBox, '*')
formattedString := boxToStr(boundedBox)
return formattedString
}
func crossFillArr(str string) [][]byte {
arr := make([][]byte, len(str))
for i := range arr {
arr[i] = make([]byte, len(str))
}
for i := 0; i < len(str); i++ {
for j := 0; j < len(str)-i; j++ {
arr[i][j] = str[i+j]
}
}
return arr
}
func fillArr(str string) [][]byte {
arr := make([][]byte, len(str))
for i := range arr {
rowArray := make([]byte, len(str))
for j := range rowArray {
rowArray[j] = str[j]
}
arr[i] = rowArray
}
return arr
}
func alternateCapsBoxFill(arr [][]byte) [][]byte {
caps := true
for i := range arr {
for j := range arr[i] {
if caps {
upperLetter := byte(unicode.ToUpper(rune(arr[i][j])))
arr[i][j] = upperLetter
caps = false
} else {
caps = true
}
}
}
return arr
}
func spaceNullBoxChars(arr [][]byte) [][]byte {
for i := range arr {
for j := range arr[i] {
if arr[i][j] == '\x00' {
arr[i][j] = ' '
}
}
}
return arr
}
func boundBox(arr [][]byte, boundChar byte) [][]byte {
rowLength := 0
columnLength := len(arr)
boundedArr := make([][]byte, columnLength+2)
for i := 0; i < columnLength; i++ {
if rowLength == 0 {
rowLength = len(arr[i])
}
rowArray := make([]byte, rowLength+2)
for j := 0; j < rowLength; j++ {
rowArray[j+1] = arr[i][j]
}
rowArray[0] = boundChar
rowArray[rowLength+1] = boundChar
boundedArr[i+1] = rowArray
}
boundArr := make([]byte, columnLength+2)
for i := 0; i < columnLength+2; i++ {
boundArr[i] = boundChar
}
boundedArr[0] = boundArr
boundedArr[columnLength+1] = boundArr
return boundedArr
}
func boxToStr(arr [][]byte) string {
byteStr := bytes.Join(arr, []byte{'\n'})
finalStr := string(byteStr)
return finalStr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment