Reversing strings in GO











up vote
-1
down vote

favorite












I'm trying to invert a string in go but I'm having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are called runes here. I tried to do some type conversions to do the assignments, but so far I could not.



The idea here is to generate 5 strings with random characters of sizes 100, 200, 300, 400 and 500 and then invert their characters. I was able to make C work with ease, but in GO, the language returns an error saying that it is not possible to perform the assignment.



 func inverte() {
var c = "A"
var strs, aux string

rand.Seed(time.Now().UnixNano())
// Gera 5 vetores de 100, 200, 300, 400, e 500 caracteres
for i := 1; i < 6; i++ {
strs = randomString(i * 100)
fmt.Print(strs)

for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
aux = strs[i2]
strs[i2] = strs[j]
strs[j] = aux
}
}
}









share|improve this question


























    up vote
    -1
    down vote

    favorite












    I'm trying to invert a string in go but I'm having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are called runes here. I tried to do some type conversions to do the assignments, but so far I could not.



    The idea here is to generate 5 strings with random characters of sizes 100, 200, 300, 400 and 500 and then invert their characters. I was able to make C work with ease, but in GO, the language returns an error saying that it is not possible to perform the assignment.



     func inverte() {
    var c = "A"
    var strs, aux string

    rand.Seed(time.Now().UnixNano())
    // Gera 5 vetores de 100, 200, 300, 400, e 500 caracteres
    for i := 1; i < 6; i++ {
    strs = randomString(i * 100)
    fmt.Print(strs)

    for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
    aux = strs[i2]
    strs[i2] = strs[j]
    strs[j] = aux
    }
    }
    }









    share|improve this question
























      up vote
      -1
      down vote

      favorite









      up vote
      -1
      down vote

      favorite











      I'm trying to invert a string in go but I'm having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are called runes here. I tried to do some type conversions to do the assignments, but so far I could not.



      The idea here is to generate 5 strings with random characters of sizes 100, 200, 300, 400 and 500 and then invert their characters. I was able to make C work with ease, but in GO, the language returns an error saying that it is not possible to perform the assignment.



       func inverte() {
      var c = "A"
      var strs, aux string

      rand.Seed(time.Now().UnixNano())
      // Gera 5 vetores de 100, 200, 300, 400, e 500 caracteres
      for i := 1; i < 6; i++ {
      strs = randomString(i * 100)
      fmt.Print(strs)

      for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
      aux = strs[i2]
      strs[i2] = strs[j]
      strs[j] = aux
      }
      }
      }









      share|improve this question













      I'm trying to invert a string in go but I'm having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are called runes here. I tried to do some type conversions to do the assignments, but so far I could not.



      The idea here is to generate 5 strings with random characters of sizes 100, 200, 300, 400 and 500 and then invert their characters. I was able to make C work with ease, but in GO, the language returns an error saying that it is not possible to perform the assignment.



       func inverte() {
      var c = "A"
      var strs, aux string

      rand.Seed(time.Now().UnixNano())
      // Gera 5 vetores de 100, 200, 300, 400, e 500 caracteres
      for i := 1; i < 6; i++ {
      strs = randomString(i * 100)
      fmt.Print(strs)

      for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
      aux = strs[i2]
      strs[i2] = strs[j]
      strs[j] = aux
      }
      }
      }






      string go inversion reversion






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 0:41









      Valney Faria

      35




      35
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.



          Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.



          For example (Go Playground):



          func reverse(s string) string {
          rs := rune(s)
          for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
          rs[i], rs[j] = rs[j], rs[i]
          }
          return string(rs)
          }

          func main() {
          fmt.Println(reverse("Hello, World!"))
          // !dlroW ,olleH
          fmt.Println(reverse("Hello, 世界!"))
          // !界世 ,olleH
          }


          There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.






          share|improve this answer























          • A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
            – David Maze
            Nov 11 at 1:37










          • @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
            – maerics
            Nov 11 at 5:22











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244824%2freversing-strings-in-go%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.



          Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.



          For example (Go Playground):



          func reverse(s string) string {
          rs := rune(s)
          for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
          rs[i], rs[j] = rs[j], rs[i]
          }
          return string(rs)
          }

          func main() {
          fmt.Println(reverse("Hello, World!"))
          // !dlroW ,olleH
          fmt.Println(reverse("Hello, 世界!"))
          // !界世 ,olleH
          }


          There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.






          share|improve this answer























          • A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
            – David Maze
            Nov 11 at 1:37










          • @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
            – maerics
            Nov 11 at 5:22















          up vote
          1
          down vote



          accepted










          As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.



          Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.



          For example (Go Playground):



          func reverse(s string) string {
          rs := rune(s)
          for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
          rs[i], rs[j] = rs[j], rs[i]
          }
          return string(rs)
          }

          func main() {
          fmt.Println(reverse("Hello, World!"))
          // !dlroW ,olleH
          fmt.Println(reverse("Hello, 世界!"))
          // !界世 ,olleH
          }


          There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.






          share|improve this answer























          • A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
            – David Maze
            Nov 11 at 1:37










          • @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
            – maerics
            Nov 11 at 5:22













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.



          Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.



          For example (Go Playground):



          func reverse(s string) string {
          rs := rune(s)
          for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
          rs[i], rs[j] = rs[j], rs[i]
          }
          return string(rs)
          }

          func main() {
          fmt.Println(reverse("Hello, World!"))
          // !dlroW ,olleH
          fmt.Println(reverse("Hello, 世界!"))
          // !界世 ,olleH
          }


          There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.






          share|improve this answer














          As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.



          Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.



          For example (Go Playground):



          func reverse(s string) string {
          rs := rune(s)
          for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
          rs[i], rs[j] = rs[j], rs[i]
          }
          return string(rs)
          }

          func main() {
          fmt.Println(reverse("Hello, World!"))
          // !dlroW ,olleH
          fmt.Println(reverse("Hello, 世界!"))
          // !界世 ,olleH
          }


          There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 1:06

























          answered Nov 11 at 0:45









          maerics

          102k28198246




          102k28198246












          • A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
            – David Maze
            Nov 11 at 1:37










          • @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
            – maerics
            Nov 11 at 5:22


















          • A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
            – David Maze
            Nov 11 at 1:37










          • @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
            – maerics
            Nov 11 at 5:22
















          A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
          – David Maze
          Nov 11 at 1:37




          A similar approach using (unicode/utf8).DecodeLastRuneInString might save an extra array/translation.
          – David Maze
          Nov 11 at 1:37












          @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
          – maerics
          Nov 11 at 5:22




          @DavidMaze neat idea, I can't get a benchmark to run faster than the above method or work with unicode edge cases though.
          – maerics
          Nov 11 at 5:22


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244824%2freversing-strings-in-go%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python