How to return a blank rune
Asked Answered
L

3

9

I'm looking at the string.Map function which must take a mapping function which returns a rune. I would like to eliminate runes that resolves false with a call to: unicode.IsPrint()

func Map(mapping func(rune) rune, s string) string

My function looks something like this:

func main() { 
func CleanUp(s string) string {

    clean := func(r rune) rune {
        if unicode.IsPrint(r) || r == rune('\n') {
            return r
        }
        return rune('')
    }

strings.Map(clean, s)
}

It should clean something like this "helloworld ' \x10" to "helloworld ' "

But rune('') is invalid. How can I return a blank or empty rune?

Lyon answered 4/9, 2018 at 21:15 Comment(2)
Try declaring a rune, not giving it a value and returning it golang.org/doc/go1#runeAmmunition
Tried this already: missing argument to conversion to rune: rune()Lyon
S
6

If you want to eliminate runes, a "blank rune" is not the way to go. That would not eliminate anything.

Assuming you're talking about strings.Map, the docs say

If mapping returns a negative value, the character is dropped from the string with no replacement.

Have your mapper return a negative value to indicate that a rune should be discarded.

Soandso answered 4/9, 2018 at 21:35 Comment(0)
A
5

From what I understand, a rune is actually an integer value mapped to a unicode character, so this piece of code actually returns the \0 character if the condition check fails:

package main

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

func main() {
    fmt.Println(CleanUp("helloworld ' \x10"))
}

func CleanUp(s string) string {

    clean := func(r rune) rune {
        if unicode.IsPrint(r) || r == rune('\n') {
            return r
        }
        return rune(0)
    }

    return strings.Map(clean, s)
}

Outputs

helloworld '

Ammunition answered 4/9, 2018 at 21:30 Comment(4)
I see this in my test: expected: "hello ' " actual : "hello ' \x00"Lyon
Try it here: play.golang.org/p/UNH02IuXQJL Works for me with your yo exampleAmmunition
I used the playground but my test shows a different result including \x00, rune(-1) worksLyon
rune(0) part is what I was looking for to create a blank runeBosnia
B
0

Here is an example using the negative return value:

package main

import (
   "strings"
   "unicode"
)

func clean(r rune) rune {
   if r == '\n' || unicode.IsPrint(r) {
      return r
   }
   return -1
}

func main() { 
   s := strings.Map(clean, "helloworld ' \x10")
   println(s == "helloworld ' ")
}
Bezanson answered 5/7, 2021 at 3:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.