英文:
How can we handle special characters like "1¼" which I want to display as "1¼"
问题
你好!要将文本中的"1¼"或"¼"转换为"¼",你可以使用Golang中的字符串替换函数。以下是一个示例代码:
package main
import (
"fmt"
"strings"
)
func main() {
text := "Your text with 1¼ or ¼"
// 使用 strings.Replace 函数进行替换
replacedText := strings.Replace(text, "1¼", "¼", -1)
replacedText = strings.Replace(replacedText, "¼", "¼", -1)
fmt.Println(replacedText)
}
在上面的示例中,我们使用了strings.Replace
函数来替换文本中的特定字符串。你可以根据需要多次调用该函数,以替换所有的"1¼"或"¼"。请将你的文本赋值给text
变量,并在strings.Replace
函数中指定要替换的字符串和替换后的字符串。
希望这可以帮助到你!如果你有任何其他问题,请随时问我。
英文:
My database contains text encoded as "1¼" or "¼" which I want to display as "¼". The text that may contains such characters is very large.
How can we achieve this using Golang?
答案1
得分: 2
正如Wumpus指出的那样,看起来是编码混乱的问题。修复它的一种简单方法是将字符串强制转换回utf-8,假设它是ISO-8869-1(Latin-1)编码。
你所拥有的字符串具有以下**[]rune
**{194, 188}
。
编码为utf-8后,具有具体字节**[]byte
**{195, 130, 194, 188}
。
为了正确显示它,你需要使它具有正确的字节。实际上,你的字符串将单个字节编码为符文,所以我们需要反转这个过程。
mistaken := // 你错误的字符串
correct := []byte{}
for _, r := range(mistaken) { // 按符文遍历
correct = append(correct, byte(r)) // 强制转换为字节(0-255)
}
fmt.Println(string(correct)) // 应该打印 "¼"
至于可能导致这个问题的原因,你是否使用正确的编码从数据库中读取文本?
英文:
As Wumpus points out, it looks like an encoding mixup. One easy way to fix it is to force-convert your strings back into utf-8 from what I assume is ISO-8869-1 (Latin-1).
The string you have has the following []rune
{194, 188}
.
Encoded as utf-8, has the concrete bytes []byte
{195, 130, 194, 188}
To get it to display correctly, you need it so that it has the correct bytes. Essentially, your string is encoding individual bytes as runes, so we need to reverse that.
mistaken := // Your erroneous string
correct := []byte{}
for _, r := range(mistaken) { // Range by runes
correct = append(correct, byte(r)) // Force conversion to byte (0-255)
}
fmt.Println(string(correct)) // Should print "¼"
As for what might be causing this problem, are you reading in the text from your database with the correct encoding?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论