• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 592
  • Last Modified:

swapping string first and last character

Hi,

I am trying to swap given string first and last character.
If I pass world i should get 'dorlw'

I found below link and code
http://www.wikihow.com/Manipulate-Strings-in-Java


String str="hello";
char[] charArray=str.toCharArray();
int indexOfLastChar=charArray.length-1;
for(int i=0;i<charArray.length/2;i++){
char temp=chatArray[i];
charArray[1]=charArray[indexOfLastChar-i];
charArray[indexOfLastChar-i]=temp;
}
String reversedStr=new String(charArray)
System.out.println("reversed string"+str+reversedStr);

Open in new window



I have not understood below line

for(int i=0;i<charArray.length/2;i++){


Is there is any easy  simple way to do it. Please advise
0
gudii9
Asked:
gudii9
  • 16
  • 12
  • 3
  • +3
5 Solutions
 
gudii9Author Commented:
i think substring approach mentioned in previous post is better right?

I wonder why they are deviding by two


for(int i=0;i<charArray.length/2;i++){

please advise
0
 
CEHJCommented:
Why have you essentially asked the same question again?
0
 
CEHJCommented:
Or is it now your intention to reverse a string (since that's what their code attempts to do)?
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
krakatoaCommented:
If I pass world i should get 'dorlw'

You won't get this output if you pass in "hello". BTW.
0
 
gudii9Author Commented:
oh they are reversing the string here?

I did not understand the logic behind it. Please advise.
0
 
ozoCommented:
It swaps the first and last characters, (the "W" and "d" in "World")
then the second and second-to-last, (the "o" and "l" in "World")
and so on, until it reaches the middle.
0
 
awking00Commented:
>>oh they are reversing the string here?<<
It seems that that's what they are trying to do although the code needs some corrections to actually accomplish that.
charArray(1) needs to be charArray(i) and chatArray should be charArray.
Since the length of the string is 5, the indexes run from 0 to 4, the length divided by 2 is 2.5 so i goes from 0 to 2. As ozo poinsts out, the character at index 0 is swapped with the character at index 4 - 0 (or 4), the character at index 1 is swapped with the character at index 4 - 1 (or 3), and the character at index 2 is swapped with the character at index 4 - 2 (or 2). If you indeed mean to only swap the first and last characters in the string, remove the for loop.
char first = charArray[0];
char last = charArray[indexOfLastChar];
charArray[0] = last;
charArray[indexOfLastChar] = first;
If you really want to just reverse the string, I would use something like the StringBuilder class -
String str = 'hello';
StringBuilder sb = new StringBuilder(str);
StringBuilder revsb = sb.reverse();
String reverseString - revsb.toString();
0
 
awking00Commented:
Typo, the last line was meant to be
String reverseString = revsb.toString();
0
 
CEHJCommented:
Yes, or just


String olleh = new StringBuilder("hello").reverse().toString();
0
 
awking00Commented:
CEHJ,
I broke the process down into individual steps to, hopefully, make it easier to understand the code, but it's a good lesson you point out that frequently multiple steps can be combined into one that accomplishes the same objective with fewer lines of code and less typing (decreasing the opportunity for typos).
0
 
gudii9Author Commented:
public class aa {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Test2 t=new Test2();
        System.out.println(t.front3(null));
        
	}
	
	public void front3(){
	
	String str="hello";
	char[] charArray=str.toCharArray();
	int indexOfLastChar=charArray.length-1;
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];
	charArray[1]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;
	}
	String reversedStr=new String(charArray);
	System.out.println("reversed string"+str+reversedStr);
	}
}

Open in new window


when i ran as above i see null pointer exception. How to modify the code to see reversed string?
please advise
0
 
ozoCommented:
public static void main(String[] args) {
            // TODO Auto-generated method stub
          //        Test2 t=new Test2();
            front3();
       
      }
0
 
gudii9Author Commented:
public class aa {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       // Test2 t=new Test2();
       // System.out.println(t.front3(null));
		front3();
	}
	
	public static void front3(){
	
	String str="hello";
	char[] charArray=str.toCharArray();
	int indexOfLastChar=charArray.length-1;
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];
	charArray[1]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;
	}
	String reversedStr=new String(charArray);
	System.out.println("actual string "+str+" reversed string "+reversedStr);
	}
}

Open in new window


As above i have to put static also for front3() method.

But my output is bit odd.

Please advise
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You certainly find the most obscure, subtle ways to get a program wrong! ;)  On the first read through, I couldn't find where the problem was. So I ran the code thinking there was no issue, but sure enough it wasn't correct. Then I finally spotted it.... Line 19 of the snippet that you posted above, you need to change the index that you are using for charArray from 1 to i, so that it looks like this...
	charArray[i]=charArray[indexOfLastChar-i];
	          ^

Open in new window

0
 
gudii9Author Commented:
public class aa {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       // Test2 t=new Test2();
       // System.out.println(t.front3(null));
		front3();
	}
	
	public static void front3(){
	
	String str="hello";
	char[] charArray=str.toCharArray();
	int indexOfLastChar=charArray.length-1;
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];
	charArray[i]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;
	}
	String reversedStr=new String(charArray);
	System.out.println("actual string "+str+" reversed string "+reversedStr);
	}
}

Open in new window


once i change like above i get
actual string hello reversed string olleh
0
 
gudii9Author Commented:
How the reversing happening in below 4 lines of code. Please advise
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];
	charArray[i]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;

Open in new window

0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I'd suggest that you use a debugger (I believe you use Eclispe and it is quite useful for debugging) to step through the code and watch the variables involved. It will give you a good idea of what is happening.
0
 
awking00Commented:
I pointed out the issue of changing the value inside the brackets of charArray[] from 1 to i (note - I used parentheses instead of brackets since EE interprets the i inside of brackets to indicate italics and expects a closing tag of /i inside of brackets at the end) in my response, ID: 40350600, as well as explaining what is happening in the code to reverse the string. What about that explanation do you not understand?
0
 
gudii9Author Commented:
I debugged as attached.

I wonder why

charArray.length/2

also why
temp is created

why charArray[i]=charArray[indexOfLastChar-i];

Open in new window


why it is subtracted i from >>>>indexOfLastChar-i
Debug.docx
0
 
gudii9Author Commented:
I also see the yellow highlighted lines not sure what they mean while debugging as attached in last post. Please advise
0
 
awking00Commented:
Let's assume the string, str, initially has a value of "abcde" then the character array, charArray,
gets set to str.toCharArray() producing the following charArray values:
charArray[0] = 'a'
charArray[1] = 'b'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'e'
with the length of the array = 5 so the index of the last character is = 5 - 1 or 4.
The for loop then starts with the value of i = 0, increments i by 1 until i is less than 5/2 or 2.5
(this is to define the midway index of the string), so the first iteration of the loop sets the temp
variable to the value of charArray[i=0] which is equal to 'a',
then sets the value of the charArray at index 0 (i.e. the value of i)
to the value of the charArray at index 4 (i.e. indexOfLastChar - i=0) which is 'e'.
At this point the array has the following values:
charArray[0] = 'e'
charArray[1] = 'b'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'e'
The value of the charArray at index 4 (i.e. indexOfLastChar - i=0) is then set to the value of temp or 'a'
producing the following values for charArray:
charArray[0] = 'e'
charArray[1] = 'b'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'a'
The next iteration of the for loop uses a value of i=1, so the
value of temp becomes the value of charArray[i=1] which is equal to 'b',
then sets the value of the charArray at index 1 (i.e. the new value of i)
to the value of the charArray at index 3 (i.e. indexOfLastChar - i=1) which is 'd'.
Now the array has the following values:
charArray[0] = 'e'
charArray[1] = 'd'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'a'
The value of the charArray at index 3 (i.e. indexOfLastChar - i=1) is then set to the value of temp
which is now 'b'
producing the following values for charArray:
charArray[0] = 'e'
charArray[1] = 'd'
charArray[2] = 'c'
charArray[3] = 'b'
charArray[4] = 'a'
The next iteration of the for loop uses a value of i=2, so the
value of temp becomes the value of charArray[i=2] which is equal to 'c',
then sets the value of the charArray at index 2 (i.e. the new value of i)
to the value of the charArray at index 2 (i.e. indexOfLastChar - i=1) which is 'c'.
Now the array has the following values:
charArray[0] = 'e'
charArray[1] = 'd'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'a'
The value of the charArray at index 2 (i.e. indexOfLastChar - i=2) is then set to the value of temp
which is now 'c'
producing the following values for charArray:
charArray[0] = 'e'
charArray[1] = 'd'
charArray[2] = 'c'
charArray[3] = 'b'
charArray[4] = 'a'
Note that because i = indexOfLastChar - i, this iteration makes the value of temp, the value of
charArray[ i], and the value of charArray[indexOfLastChar - i] all equal to 'c'.
The next iteration of the loop uses a value i=3 and, because that value is less than 5/2 breaks
out of the loop so the final charArray can be converted to a string which is the reversal of the
original string.
The highlighted lines merely show the values of i, charArray[ i], and charArray[indexOfLastChar - i]
as you step through the code. Hope this helps you understand.
0
 
awking00Commented:
Note where i is contained within the square brackets, I used a space in front of the i so that EE doesn't consider it to mean something should be italicized.
0
 
awking00Commented:
The next iteration of the loop uses a value i=3 and, because that value is less than 5/2  was meant to be
The next iteration of the loop uses a value i=3 and, because that value is greater than 5/2
0
 
gudii9Author Commented:
String olleh = new StringBuilder("hello").reverse().toString();
		System.out.println("olleh-->"+olleh);

Open in new window


I got output
olleh-->olleh

Above also worked. Is it is good idea to use StringBuilder all the time when we want to manipulate String to make it simple and easy?
 Please advise
0
 
awking00Commented:
As I mentioned in my first post, if you want to just reverse a string, then StringBuilder provides a simpler method than the code we've been working with that creates a char array from the string then swaps the first character with the last character, the second with the next to last, the third with the second from last until it hits the middle of the array, then converts it back to a string. You need to understand that a String is immutable meaning it can not be modified without some manipulation such as StringBuilder or using a char array or some other method, then converting it back to another String. As for using StringBuilder or another method for manipulating a String, it likely depends on the complexity of the manipulation required. For example, adding the character 'x' to a String is probably easier doing something like -
String str = "abc";
String newstr = str.concat("x");
rather than using a StringBuilder with the append method to add the "x", then converting back to a new String, but StringBuilder is probably a better way to go for more complex manipulations.
0
 
awking00Commented:
I should have said -
You need to understand that a String is immutable meaning it can not be modified period. Only with some manipulation using other objects such as StringBuilder or character arrays can you create a new String based on the characters of an initial String.
0
 
gudii9Author Commented:
I was reading your posts in detail now
variable to the value of charArray[i=0] which is equal to 'a',
then sets the value of the charArray at index 0 (i.e. the value of i)

you mean as below right?

variable to the value of charArray[i=0] which is equal to 'a',
then sets the value of the charArray at index 1 (i.e. the value of 'b')
0
 
gudii9Author Commented:
Let's assume the string, str, initially has a value of "abcde" then the character array, charArray,
gets set to str.toCharArray() producing the following charArray values:
charArray[0] = 'a'
charArray[1] = 'b'
charArray[2] = 'c'
charArray[3] = 'd'
charArray[4] = 'e'
with the length of the array = 5 so the index of the last character is = 5 - 1 or 4.
The for loop then starts with the value of i = 0, increments i by 1 until i is less than 5/2 or 2.5
(this is to define the midway index of the string), so the first iteration of the loop sets the temp
variable to the value of charArray[i=0] which is equal to 'a',

I have understood above lines. But i could not follow clearly afterwards next lines. Can you please elaborate more later lines.
0
 
awking00Commented:
Don't know how much more I can elaborate -
The loop for the first time around says set temp = 'a' (the current first element in the array), set the first element in the array to 'e' (the current last element in the array), then set the last element in the array to temp (i.e. 'a').
The loop for the second time around says set temp = 'b' (the current first element in the array), set the second element in the array to 'd' (the current next to last element in the array), then set the next to last element in the array to temp (i.e. which is now 'b').
The third time the loop breaks out because the value of i in now = 2 (the integer value of 5 divided by 2) which is not less than 2, so the array is then converted back to a new string which is the reverse of the original string.

Try this - take the ace, deuce, trey, four, and five of hearts from a deck of cards and place them from left to right in that order.
Then starting with the first card on the left (the ace), put that card in your pocket (labeled temp), then take the first card from the right (the five) and put it where the ace was before, then take the ace out of your pocket and put it where the five was before.
Next take the second card from the left (the deuce) and put that in your pocket, then take the second card from the right (the four) and put it where the deuce was before, then take the deuce out of your pocket and put it where the four was before.
Repeat the process until you reach the middle of the row of cards. Now the row of cards are in the order from left to right of five, four, trey, deuce, and ace.

Note - I actually misspoke in my explanation, In the example the third loop would not occur because the integer value of the array length divided by 2 is only 2 (i.e. not 2.5), so the loop actually stops when i = 2 (which is not less than 2)
0
 
awking00Commented:
The fourth line of my last response should have read "The loop for the second time around says set temp = 'b' (the current second element in the array) ..." and not "The loop for the second time around says set temp = 'b' (the current first element in the array) ...
0
 
gudii9Author Commented:
what happens in the for loop instead of

i<charArray.length/2

if they give like below

i<charArray.length
0
 
gudii9Author Commented:
when i removed /2
public class Test5 {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       // Test2 t=new Test2();
       // System.out.println(t.front3(null));
		front3();
	}
	
	public static void front3(){
	
	String str="hello";
	char[] charArray=str.toCharArray();
	int indexOfLastChar=charArray.length-1;
	for(int i=0;i<charArray.length;i++){
	char temp=charArray[i];
	charArray[i]=charArray[indexOfLastChar-i];
	charArray[indexOfLastChar-i]=temp;
	}
	String reversedStr=new String(charArray);
	System.out.println("actual string "+str+" reversed string "+reversedStr);
	}
}

Open in new window


i got output as below(it did not reverse the string).

actual string hello reversed string hello

I wonder why it did not reverse?
0
 
gudii9Author Commented:
so the for loop runs 2.5 times for below code

for(int i=0;i<charArray.length/2;i++)


how it run 0.5 times after looping 2 times

Please advise
0
 
gudii9Author Commented:
public class Test5 {
	//public static void main(args[] String){
		
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       // Test2 t=new Test2();
       // System.out.println(t.front3(null));
		front3();
	}
	
	public static void front3(){
	
	String str="hellom";
	char[] charArray=str.toCharArray();//charArray has h e l l o in index positions 0 1 2 3 4 
	int indexOfLastChar=charArray.length-1;//4
	for(int i=0;i<charArray.length/2;i++){
	char temp=charArray[i];////first iteration temp-->h  second iteration--->e
	charArray[i]=charArray[indexOfLastChar-i];//first iteration--> o e l l o second iteration--->o l l l h
	charArray[indexOfLastChar-i]=temp;//first iteration--> o e l l h second iteration--->o l l e h
	}
	String reversedStr=new String(charArray);
	System.out.println("actual string "+str+" reversed string "+reversedStr);
	}
}

Open in new window


I saw as above.

Looks like iteration happening in for loop only 2 times when i=0 and when i=1
0
 
gudii9Author Commented:
i wonder why iteration  did not happen  when i=2.

I mean when i=2 instead of control going inside the for loop(since 2<2.5) it came out of the for loop which is not clear to me.

Also if the string has even number of characters let us say "abcdef"
Does it still work. Seems it is working. I wonder how it is working for string has even number of characters let us say "abcdef"(in this case 6 is legth so devided by 2 would be 3)
0
 
awking00Commented:
It works because i is defined as an int and 5/2 as an int datatype in Java = 2 and not 2.5 and 2 is not less than 2. To get 5/2 to be 2.5 you would need to make it a double or float datatype. The String will work with even characters in the same way  In your sample case, 6/2 = 3 and 3 is not less than 3, so it would swap index 0 with 5, index 1 with 4, index 2, with 3, then break out of the loop.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
And to answer a previous question of yours...

when i removed /2

i got output as below(it did not reverse the string).

(Again, following this through with the debugger should have given you a good idea but...) What is happening is that the characters are getting swapped TWICE. ie, after the first two iterations through the loop, the characters in the array spell "olleh" but then since you keep the loop going further the e and the l get swapped again making, "oellh" and then the h and the o get swapped again making, "hello". So it IS actually reversing, but then it reverses it again returning it to the original string.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 16
  • 12
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now