Reversing a string - two approaches












1












$begingroup$


Test Case:
Input- "I'm hungry!"
Output- "!yrgnuh m'I"



Approach 1: In this approach, I used a empty string and bind it with the input string reversely.



public static class ReverseString {

public static string Reverse (string input) {

//bind the string to an empty string reversly
var reversedString = "";

//check if the input is empty
if (input == "")
{
return "";
}
else
{
for (int i = input.Length - 1; i >= 0; i--)
{
reversedString += input[i];
}
return reversedString;
}
}
}


Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.



public static class ReverseString {
public static string Reverse (string input) {

char chars = new char[input.Length];

for(int i = 0, j = input.Length -1; i <= j; i++, j--)
{
chars[i] = input[j];
chars[j] = input[i];
}

return new string(chars);
}
}


There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?










share|improve this question











$endgroup$

















    1












    $begingroup$


    Test Case:
    Input- "I'm hungry!"
    Output- "!yrgnuh m'I"



    Approach 1: In this approach, I used a empty string and bind it with the input string reversely.



    public static class ReverseString {

    public static string Reverse (string input) {

    //bind the string to an empty string reversly
    var reversedString = "";

    //check if the input is empty
    if (input == "")
    {
    return "";
    }
    else
    {
    for (int i = input.Length - 1; i >= 0; i--)
    {
    reversedString += input[i];
    }
    return reversedString;
    }
    }
    }


    Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.



    public static class ReverseString {
    public static string Reverse (string input) {

    char chars = new char[input.Length];

    for(int i = 0, j = input.Length -1; i <= j; i++, j--)
    {
    chars[i] = input[j];
    chars[j] = input[i];
    }

    return new string(chars);
    }
    }


    There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?










    share|improve this question











    $endgroup$















      1












      1








      1





      $begingroup$


      Test Case:
      Input- "I'm hungry!"
      Output- "!yrgnuh m'I"



      Approach 1: In this approach, I used a empty string and bind it with the input string reversely.



      public static class ReverseString {

      public static string Reverse (string input) {

      //bind the string to an empty string reversly
      var reversedString = "";

      //check if the input is empty
      if (input == "")
      {
      return "";
      }
      else
      {
      for (int i = input.Length - 1; i >= 0; i--)
      {
      reversedString += input[i];
      }
      return reversedString;
      }
      }
      }


      Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.



      public static class ReverseString {
      public static string Reverse (string input) {

      char chars = new char[input.Length];

      for(int i = 0, j = input.Length -1; i <= j; i++, j--)
      {
      chars[i] = input[j];
      chars[j] = input[i];
      }

      return new string(chars);
      }
      }


      There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?










      share|improve this question











      $endgroup$




      Test Case:
      Input- "I'm hungry!"
      Output- "!yrgnuh m'I"



      Approach 1: In this approach, I used a empty string and bind it with the input string reversely.



      public static class ReverseString {

      public static string Reverse (string input) {

      //bind the string to an empty string reversly
      var reversedString = "";

      //check if the input is empty
      if (input == "")
      {
      return "";
      }
      else
      {
      for (int i = input.Length - 1; i >= 0; i--)
      {
      reversedString += input[i];
      }
      return reversedString;
      }
      }
      }


      Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.



      public static class ReverseString {
      public static string Reverse (string input) {

      char chars = new char[input.Length];

      for(int i = 0, j = input.Length -1; i <= j; i++, j--)
      {
      chars[i] = input[j];
      chars[j] = input[i];
      }

      return new string(chars);
      }
      }


      There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?







      c# performance strings programming-challenge comparative-review






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago









      200_success

      129k15152415




      129k15152415










      asked 3 hours ago









      AKdeBergAKdeBerg

      434




      434






















          1 Answer
          1






          active

          oldest

          votes


















          3












          $begingroup$

          Clarity of Approaches



          With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.



          Unnecessary Code



          In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.



          Performance



          As you may know, strings are immutable objects in .Net. It is good practice to use a StringBuilder to create strings in this way, like so:



          var reversedString = new StringBuilder();
          for (int i = input.Length - 1; i >= 0; i--)
          {
          reversedString.Append(input[i]);
          }
          return reversedString.ToString();





          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f211873%2freversing-a-string-two-approaches%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









            3












            $begingroup$

            Clarity of Approaches



            With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.



            Unnecessary Code



            In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.



            Performance



            As you may know, strings are immutable objects in .Net. It is good practice to use a StringBuilder to create strings in this way, like so:



            var reversedString = new StringBuilder();
            for (int i = input.Length - 1; i >= 0; i--)
            {
            reversedString.Append(input[i]);
            }
            return reversedString.ToString();





            share|improve this answer









            $endgroup$


















              3












              $begingroup$

              Clarity of Approaches



              With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.



              Unnecessary Code



              In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.



              Performance



              As you may know, strings are immutable objects in .Net. It is good practice to use a StringBuilder to create strings in this way, like so:



              var reversedString = new StringBuilder();
              for (int i = input.Length - 1; i >= 0; i--)
              {
              reversedString.Append(input[i]);
              }
              return reversedString.ToString();





              share|improve this answer









              $endgroup$
















                3












                3








                3





                $begingroup$

                Clarity of Approaches



                With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.



                Unnecessary Code



                In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.



                Performance



                As you may know, strings are immutable objects in .Net. It is good practice to use a StringBuilder to create strings in this way, like so:



                var reversedString = new StringBuilder();
                for (int i = input.Length - 1; i >= 0; i--)
                {
                reversedString.Append(input[i]);
                }
                return reversedString.ToString();





                share|improve this answer









                $endgroup$



                Clarity of Approaches



                With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.



                Unnecessary Code



                In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.



                Performance



                As you may know, strings are immutable objects in .Net. It is good practice to use a StringBuilder to create strings in this way, like so:



                var reversedString = new StringBuilder();
                for (int i = input.Length - 1; i >= 0; i--)
                {
                reversedString.Append(input[i]);
                }
                return reversedString.ToString();






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 3 hours ago









                Joe CJoe C

                647210




                647210






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211873%2freversing-a-string-two-approaches%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

                    GameSpot

                    日野市

                    Tu-95轟炸機