How to remove newlines from a string Go

2 Answers

0 votes
package main

import (
    "fmt"
    "strings"
)

func removeNewlines(s string) string {
    // Replace both Unix (\n) and Windows (\r\n) newline characters
    s = strings.ReplaceAll(s, "\n", "")
    s = strings.ReplaceAll(s, "\r", "")
    return s
}

func main() {
    s := "c# \n  c c++  \n java python\ngo\n";

    result := removeNewlines(s)

    fmt.Println(result)
}



/*
run:

c#   c c++   java pythongo

*/

 



answered Feb 22 by avibootz
0 votes
package main

import (
    "fmt"
    "strings"
    "unicode"
)

func removeNewlines(s string) string {
    var b strings.Builder
    b.Grow(len(s))

    lastWasSpace := false

    for _, r := range s {
        if unicode.IsSpace(r) {
            if !lastWasSpace {
                b.WriteRune(' ')
                lastWasSpace = true
            }
        } else {
            b.WriteRune(r)
            lastWasSpace = false
        }
    }

    // Trim trailing space
    out := strings.TrimSpace(b.String())
    return out
}

func main() {
    s := "c# \n  c c++  \n java python\ngo\n";

    result := removeNewlines(s)

    fmt.Println(result) // result without extra spaces
}



/*
run:

c# c c++ java python go

*/

 



answered Feb 22 by avibootz
...