How can we handle special characters like "1¼" which I want to display as "1¼"

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

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?

huangapple
  • 本文由 发表于 2015年6月25日 22:08:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/31052766.html
匿名

发表评论

匿名网友

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

确定