5

I started learning go and I want to implement some algorithm. I can iterate over strings and then get chars, but these chars are Unicode numbers.

How to concatenate chars into strings in go? Do you have some reference? I was unable to find anything about primitives in official page.

1
  • well what the hell is a "char"? There is no such type in Go Commented Jun 26, 2013 at 22:09

4 Answers 4

10

Iterating over strings using range gives you Unicode characters while iterating over a string using an index gives you bytes. See the spec for runes and strings as well as their conversions.

As The New Idiot mentioned, strings can be concatenated using the + operator.

The conversion from character to string is two-fold. You can convert a byte (or byte sequence) to a string:

string(byte('A'))

or you can convert a rune (or rune sequence) to a string:

string(rune('µ'))

The difference is that runes represent Unicode characters while bytes represent 8 bit values.

But all of this is mentioned in the respective sections of the spec I linked above. It's quite easy to understand, you should definitely read it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for explaining difference between iterating with index and range
3

you can convert a []rune to a string directly:

string([]rune{'h', 'e', 'l', 'l', 'o', '☃'})

http://play.golang.org/p/P9vKXlo47c

as for reference, it's in the Conversions section of the Go spec, in the section titled "Conversions to and from a string type"

http://golang.org/ref/spec#Conversions

as for concatenation, you probably don't want to concatenate every single character with the + operator, since that will perform a lot of copying under the hood. If you're getting runes in one at a time and you're not building an intermediate slice of runes, you most likely want to use a bytes.Buffer, which has a WriteRune method for this sort of thing. http://golang.org/pkg/bytes/#Buffer.WriteRune

Comments

2

Use +

str:= str + "a"

You can try something like this :

string1 := "abc"
character1 := byte('A')
string1 += string(character1)

Even this answer might be of help.

Comments

0

definetly worth reading @nemo's post

Iterating over strings using range gives you Unicode characters while iterating over a string using an index gives you bytes. See the spec for runes and strings as well as their conversions.

Strings can be concatenated using the + operator.

The conversion from character to string is two-fold. You can convert a byte (or byte sequence) to a string:

string(byte('A'))

or you can convert a rune (or rune sequence) to a string:

string(rune('µ'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.