Search code examples
stringgomultiline

Multiline literal string input


I created this simple code in Go to perform data processing - remove {, replace }, remove line breaks, etc. This treatment is occurring perfectly well in the func removelinebreaks() and the data is inserted in the var idsUnits as a multiline literal string, with grave quotes instead of double quotes because the data input has line breaks.

Data used:

{10F3DDED-800A-EC11-A30E-0050568A2E98}
{14F3DDED-800A-EC11-A30E-0050568A2E98}
{48B209F4-800A-EC11-A30E-0050568A2E98}

I need to improve this code by adding an input where the user is asked to insert this data into the console, instead of directly into the idsUnits variable, and then sent for normal processing in removelinebreaks()

I tried several ways but I can't get it to work. Does anyone have any ideas?

https://www.onlinegdb.com/fork/v4lTVTD02


Solution

  • You can read lines from stdin with help of bufio and split input lines like following,

    package main
    
    import (
        "bufio"
        "os"
        "fmt"
        "strings"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
        var lines []string
    
        for {
            fmt.Print("Enter text (or leave empty to finish): ")
            input, _ := reader.ReadString('\n')
            trimmedInput := strings.TrimSpace(input) // Remove leading and trailing white space
    
            if trimmedInput == "" { // Check if the input is empty (i.e., user pressed "Enter").
                break // Exit the loop if input is empty.
            }
            lines = append(lines, trimmedInput)
        }
    
        ids := strings.Join(lines, "\n")
        removelinebreaks(ids)
    }
    
    func removelinebreaks(ids string) {
        idsForRemove := ids
    
        result := strings.ReplaceAll(idsForRemove, "{", "") // Remove the {
        result = strings.ReplaceAll(result, "}", ",")       // Replace the } with ,
        result = strings.ReplaceAll(result, "\n", "")       // Remove line breaks
        result = strings.TrimSuffix(result, ",")            // Remove the last comma
        
        fmt.Println("data output:\n")
        
        fmt.Println(result)
    }