Golang : Convert spaces to tabs and back to spaces example
A simple example on how to convert spaces to tabs and convert back the tabs to spaces again in a given text string. Useful in a situation where you want to pre-parse a raw data file first before feeding to another parser for further processing.
Here you go!
package main
import (
"fmt"
"strings"
"unicode"
)
func TabToSpace(input string) string {
var result []string
for _, i := range input {
switch {
// all these considered as space, including tab \t
// '\t', '\n', '\v', '\f', '\r',' ', 0x85, 0xA0
case unicode.IsSpace(i):
result = append(result, " ") // replace tab with space
case !unicode.IsSpace(i):
result = append(result, string(i))
}
}
return strings.Join(result, "")
}
func spaceToTab(input string) string {
var result []string
for _, i := range input {
switch {
case unicode.IsSpace(i):
result = append(result, "\t")
case !unicode.IsSpace(i):
result = append(result, string(i))
}
}
return strings.Join(result, "")
}
func main() {
// text := "This is a line with a lot of spaces in between"
text := "жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ"
fmt.Println("Before: ", text)
output := spaceToTab(text)
fmt.Println("After: ", output)
fmt.Println("Back:", TabToSpace(output))
}
Output:
Before: жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ
After: жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ
Back: жѳМѭњЂЯёЧВ 一二三 handle alphabets = ขอพฮศโำฐเฦ abc世界你好123 ペツワケザユプルヂザ
References:
https://golang.org/src/unicode/graphic.go?s=3997:4022#L116
https://www.socketloop.com/tutorials/golang-read-tab-delimited-file-with-encoding-csv-package
See also : Golang : Read tab delimited file with encoding/csv package
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.2k Golang : Convert word to its plural form example
+7.7k Golang : Load DSA public key from file example
+11k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+5.6k Swift : Get substring with rangeOfString() function example
+5.4k Python : Print unicode escape characters and string
+6.2k Golang : Selection sort example
+21.6k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+11k Golang : Calculate Relative Strength Index(RSI) example
+18.7k Golang : How to make function callback or pass value from function as parameter?
+8.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+15.3k Golang : ROT47 (Caesar cipher by 47 characters) example
+10.5k Golang : How to delete element(data) from map ?