If you want to manipulate individual characters or bytes in a string,
either for re-ordering or concatenation, you should probably convert them
to slices first. Otherwise most operations you perform that generates a new
string (notable exception: sub-string) will allocate memory and copy the
relevant data so you will be doing extra work, but more importantly putting
more pressure on the memory system / garbage collector.
You can convert any string to a byte to manipulate individual bytes, or
you can convert a string to a rune to manipulate text in a unicode safe
Here's runes: http://play.golang.org/p/zvXq4OY04K
Strings.Split *does not* allocate new memory for the substrings, nor does
it copy data, but Strings.Join does. Therefore there are technically more
efficient solutions, but I like the symmetry and simplicity of the
"backwords" function. The big benefits of the approach is that:
- It respects unicode characters (manipulating bytes will likely trash
utf-8 strings that have non-ascii characters)
- The reversal code doesn't allocate, it does all its work on the original
- You have a nice framework for reducing the number of allocations even
further, for example, you could convert the entire string to rune of the
start, and have only two allocation / copy operations in total: one from
string to rune and one back, you just have to re-write the tokenizing
function, here's an example in backwords2, and it reuses the reverse
function un-altered: http://play.golang.org/p/D8A7Fi0MPv
On Thursday, April 24, 2014 3:05:37 PM UTC-7, Tong Sun wrote:
Any way to concat char to a string?http://play.golang.org/p/XqJINNoz9E
I was trying to learn go with *the word **reverse *problem BTW:
Given a string say "I am a human being" the output should reverse all
letters within each word but otherwise preserve everything.
Eg: output should be "I ma a namuh gnieb"
No build-in string reverse function or build-in stack data-structure
should be used.
Your go implementation is appreciated.
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firstname.lastname@example.org.
For more options, visit https://groups.google.com/d/optout.