Transposing and Untransposing a String in java

Posted by Will on Stack Overflow See other posts from Stack Overflow or by Will
Published on 2010-04-13T02:41:23Z Indexed on 2010/04/13 2:42 UTC
Read the original article Hit count: 375

Filed under:
|
|

I have been working on two methods that will Transpose and Untranspose a String respectively. The solutions that I have come up with both work to the best of my knowledge. I just want to know if I could have solved these problems in a simpler way. My code seems like it is too long for the task that is being performed. The first method, transpose(), will take a String as a parameter and transpose it. If "bridge" is entered, the output will be "bergid". Likewise, with the unTranspose() method, if the user enters "bergid", the output will be "bridge".

  public void transpose( String s )
  {
      String t = ""; 
      int end = s.length() - 1;


        for ( int i = 0; i < s.length()  / 2; i++ )
        {
            t += Character.toString( s.charAt( i ) ) + Character.toString( s.charAt( end ) );
            end--;
        }
        // Lenth of String is odd
        if ( s.length() % 2 == 1 )
        {
            // add character in middle of String to the end of the new String
            t+= Character.toString( s.charAt( s.length() / 2 ) );
        }

        System.out.println( t );
  }

    public void unTranspose( String s )
    {
    String t = ""; 

      // Length of String is odd
      if ( s.length() % 2 == 1 )
      {
      for ( int i = 0; i < s.length(); i+=2 )
      {
        t+= Character.toString( s.charAt( i ) );
      }

      for ( int i = s.length() - 2; i > 0; i -= 2 )
      {
        t += Character.toString( s.charAt( i ) );
      }

         System.out.println( t );
      }



   // Length of String is even
   else if ( s.length() % 2 == 0 )
   {
    for ( int i = 0; i < s.length() - 1; i+=2 )
    {
       t+= Character.toString( s.charAt( i ) );
    }

    for ( int i = s.length() - 1; i > 0; i -= 2 )
    {
        t+= Character.toString( s.charAt( i ) );
    }


    System.out.println( t );
}
   }

My code looks horrible. I'm still not used to formatting my code correctly. Please bear with me.

Thanks for your time

© Stack Overflow or respective owner

Related posts about java

Related posts about strings