Note that there are some explanatory texts on larger screens.

plurals
  1. POTransposing and Untransposing a String in java
    text
    copied!<p>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".</p> <pre><code> public void transpose( String s ) { String t = ""; int end = s.length() - 1; for ( int i = 0; i &lt; 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 &lt; s.length(); i+=2 ) { t+= Character.toString( s.charAt( i ) ); } for ( int i = s.length() - 2; i &gt; 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 &lt; s.length() - 1; i+=2 ) { t+= Character.toString( s.charAt( i ) ); } for ( int i = s.length() - 1; i &gt; 0; i -= 2 ) { t+= Character.toString( s.charAt( i ) ); } System.out.println( t ); } } </code></pre> <p>My code looks horrible. I'm still not used to formatting my code correctly. Please bear with me.</p> <p>Thanks for your time</p> <hr> <h3>Definition</h3> <pre><code> transpose ---------&gt; "123Xcba" "1a2b3cX" &lt;----------- untranspose </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload