How can do replacement "*" in another language? (speech language)


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #1

Hi there

I can do replacement “*” in English that’s okay but in Persian, Chine I have a problem.
How can fix it? (Due to “[ ]byte” it has 2 separate byte for example character " س " is " [ 216 179 ]

In other words, how can remove the "question mark "(�)?

Here is playGround :
https://play.golang.org/p/9Nd7rvatqC9

also, code review :

func main() {

	fmt.Println( replaceAtIndex2("persian ----","س",'*',0))
	fmt.Println( replaceAtIndex2("persian ----","سلام",'*',0))
	
	fmt.Println( replaceAtIndex2("chine +-+-+-","世",'*',0))
	fmt.Println( replaceAtIndex2("chine +-+-+-","世界",'*',0))
	
	fmt.Println( replaceAtIndex2("english  ====","h",'*',0))
	fmt.Println( replaceAtIndex2("english  ====","hello",'*',0))
}

func replaceAtIndex2(typeOfValue string ,str string, replacement rune, index int) string {
	fmt.Println(typeOfValue, len(str))
	fmt.Println(typeOfValue, []byte(str))
	return str[:index] + string(replacement) + str[index+1:]
}

Thanks in advance.


(Norbert Melzer) #2

You need to convert your string to a slice of runes ([]rune(str)), replace the single rune and then convert back to string. Roughly like this:

tmp := []rune(str)
tmp[index] = replacement
return string(tmp)

Can’t test though as I’m on mobile.


(Jay Ts) #3

Hi,

Norbert is definitely on the right track. In Go, runes are used for handling UTF-8 Unicode code points. When you need to support characters outside of the English language, use runes, not bytes.

Here is an example of how you can get your program to work:

https://play.golang.org/p/a3IjN_X7ANj

I commented out the 2 lines for Persian because it looks like you did something wrong in them. The last 3 arguments are reversed, compared to the Chinese and English examples, and a double quote (") is out of place.


(Norbert Melzer) #4

This is due to the fact that mixed RTL and LTR is implemented badly or worse in most browsers. Apart if that changing writing direction in a paragraph isn’t even allowed in HTML as far as I know, so I understand they are not doing much.


(Jay Ts) #5

Hi Norbert,

Oh, thanks for that! Just now I copied and pasted the code from the Go Playground to a local file, and in the file, it appears correctly as

image

So the Go Playground stores it correctly, but both Firefox and Chrome web browsers display it incorrectly (at least for my locale). That explains why the Go Playground compiled the “weird code” without error messages.