Logo

Programming-Idioms

History of Idiom 41 > diff from v17 to v18

Edit summary for version 18 by :

Version 17

2015-09-05, 19:10:44

Version 18

2015-10-29, 14:05:13

Idiom #41 Reverse a string

Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

Idiom #41 Reverse a string

Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

Code
t = reverse s :: String
Code
t = reverse s :: String
Imports
import std.range, std.array;
Imports
import std.range, std.array;
Code
auto t = "The key to learning D is to 脚踏实地".retro.array;
Code
auto t = "The key to learning D is to 脚踏实地".retro.array;
Comments bubble
Note, t is now a dchar[], which is a utf-32 encoded string. To convert back to the type of s, you need to call std.conv.to.
Comments bubble
Note, t is now a dchar[], which is a utf-32 encoded string. To convert back to the type of s, you need to call std.conv.to.
Demo URL
http://dpaste.dzfl.pl/b21510935840
Demo URL
http://dpaste.dzfl.pl/b21510935840
Code
t = s.reverse
Code
t = s.reverse
Doc URL
http://ruby-doc.org/core-1.8.6/String.html#method-i-reverse-21
Doc URL
http://ruby-doc.org/core-1.8.6/String.html#method-i-reverse-21
Code
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
   runes[i], runes[j] = runes[j], runes[i]
}
t := string(runes)
Code
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
   runes[i], runes[j] = runes[j], runes[i]
}
t := string(runes)
Comments bubble
This takes care of multi-byte runes, which count as a single character.
Comments bubble
This takes care of multi-byte runes, which count as a single character.
Origin
http://stackoverflow.com/questions/1752414/how-to-reverse-a-string-in-go#answer-10030772
Origin
http://stackoverflow.com/questions/1752414/how-to-reverse-a-string-in-go#answer-10030772
Demo URL
http://play.golang.org/p/swFXJkofzC
Demo URL
http://play.golang.org/p/swFXJkofzC