如何在Go语言中获取一个rune的十进制值?

huangapple go评论72阅读模式
英文:

How to get the decimal value for a rune in Go?

问题

我需要解析一些字符串并通过解析任何特殊字符作为'â'来清理它们,转换为&#226。这是十进制编码。我知道如何使用这个将其解析为Unicode,但我需要十进制代码。整个想法是替换这些特殊字符并返回包含转换的整个字符串,如果它们包含特殊字符的话。例如:

text := "chitâra"
text := parseNCRs(text) //可以通过引用
parseNCRs(&text) //或者通过传递指针
fmt.Println(text) //输出:"chitâra"
英文:

I need to parse some strings and clean them by parsing any special char as 'â' TO &#226. This is decimal encoding. I know how to parse it to Unicode with this, but I will need the decimal code. The whole idea is to replace those special chars and return the whole string with the conversion if they contain special characters. For example:

text := "chitâra"
text := parseNCRs(text) //can be by reference
parseNCRs(&text) //or passing the pointer
fmt.Println(text) //Outputs: "chitâra"

答案1

得分: 4

在字符串上进行范围循环,获取符文的数值。

func escape(s string) string {
    var buf bytes.Buffer
    for _, r := range s {
        if r > 127 {
            fmt.Fprintf(&buf, "&#%d;", r)
        } else {
            buf.WriteRune(r)
        }
    }
    return buf.String()
}

<kbd>[playground](http://play.golang.org/p/L9SeKO0qgW)</kbd>

如果你要转义为HTML或XML还应处理其他特殊字符

```go
func escape(s string) string {
    var buf bytes.Buffer
    for _, r := range s {
        if r > 127 || r == '<' || r == '>' || r == '&' || r == '"' || r == '\'' {
            fmt.Fprintf(&buf, "&#%d;", r)
        } else {
            buf.WriteRune(r)
        }
    }
    return buf.String()
}
英文:

Range over the string to get the numeric values of the runes.

func escape(s string) string {
  var buf bytes.Buffer
  for _, r := range s {
	if r &gt; 127 {
		fmt.Fprintf(&amp;buf, &quot;&amp;#%d;&quot;, r)
	} else {
		buf.WriteRune(r)
	}
  }
  return buf.String()
}

<kbd>playground</kbd>

If you are escaping for HTML or XML, then you should also handle other special chracters:

func escape(s string) string {
  var buf bytes.Buffer
  for _, r := range s {
	if r &gt; 127  || r == &#39;&lt;&#39; || r == &#39;&gt;&#39; || r == &#39;&amp;&#39; || r == &#39;&quot;&#39; || r = &#39;\&#39;&#39; {
		fmt.Fprintf(&amp;buf, &quot;&amp;#%d;&quot;, r)
	} else {
		buf.WriteRune(r)
	}
  }
  return buf.String()
}

huangapple
  • 本文由 发表于 2014年10月8日 01:18:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/26241584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定