多行文字字符串输入

问题描述 投票:0回答:1

我在 Go 中创建了这个简单的代码来执行数据处理 - 删除 {、替换 }、删除换行符等。 这种处理在 func removelinebreaks() 中进行得非常好,并且数据作为多行文字字符串插入到 var idsUnits 中,并使用引号而不是双引号,因为数据输入有换行符。

使用数据:

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

我需要通过添加一个输入来改进此代码,要求用户将此数据插入控制台,而不是直接插入到 idsUnits 变量中,然后发送到 removelinebreaks()

中进行正常处理

我尝试了多种方法,但无法使其发挥作用。 有人有什么想法吗?

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

string go multiline
1个回答
0
投票

您可以在 bufio 的帮助下从标准输入读取行并分割输入行,如下所示,

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.