英文:
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 > 127 {
		fmt.Fprintf(&buf, "&#%d;", 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 > 127  || r == '<' || r == '>' || r == '&' || r == '"' || r = '\'' {
		fmt.Fprintf(&buf, "&#%d;", r)
	} else {
		buf.WriteRune(r)
	}
  }
  return buf.String()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论