4

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.

nemo
  • 55,207
  • 13
  • 135
  • 135
Sławosz
  • 11,187
  • 15
  • 73
  • 106

4 Answers4

9

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.

Stephen Weinberg
  • 51,320
  • 14
  • 134
  • 113
nemo
  • 55,207
  • 13
  • 135
  • 135
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

jorelli
  • 8,064
  • 4
  • 36
  • 35
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.

Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
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('µ'))
wpmoradi
  • 51
  • 3