gudii9
asked on
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
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
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);
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
Why have you essentially asked the same question again?
Or is it now your intention to reverse a string (since that's what their code attempts to do)?
If I pass world i should get 'dorlw'
You won't get this output if you pass in "hello". BTW.
ASKER
oh they are reversing the string here?
I did not understand the logic behind it. Please advise.
I did not understand the logic behind it. Please advise.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>>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();
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]
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();
Typo, the last line was meant to be
String reverseString = revsb.toString();
String reverseString = revsb.toString();
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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).
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).
ASKER
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);
}
}
when i ran as above i see null pointer exception. How to modify the code to see reversed string?
please advise
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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);
}
}
As above i have to put static also for front3() method.
But my output is bit odd.
Please advise
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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);
}
}
once i change like above i get
actual string hello reversed string olleh
ASKER
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;
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.
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?
ASKER
I debugged as attached.
I wonder whyDebug.docx
charArray.length/2
also why
temp is created
why charArray[i]=charArray[indexOfLastChar-i];
why it is subtracted i from >>>>indexOfLastChar-i
ASKER
I also see the yellow highlighted lines not sure what they mean while debugging as attached in last post. Please advise
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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
The next iteration of the loop uses a value i=3 and, because that value is greater than 5/2
ASKER
String olleh = new StringBuilder("hello").reverse().toString();
System.out.println("olleh-->"+olleh);
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
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.
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.
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.
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.
ASKER
I was reading your posts in detail now
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')
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')
ASKER
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.
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)
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)
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) ...
ASKER
what happens in the for loop instead of
i<charArray.length/2
if they give like below
i<charArray.length
i<charArray.length/2
if they give like below
i<charArray.length
ASKER
when i removed /2
i got output as below(it did not reverse the string).
actual string hello reversed string hello
I wonder why it did not reverse?
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);
}
}
i got output as below(it did not reverse the string).
actual string hello reversed string hello
I wonder why it did not reverse?
ASKER
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
for(int i=0;i<charArray.length/2;i
how it run 0.5 times after looping 2 times
Please advise
ASKER
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);
}
}
I saw as above.
Looks like iteration happening in for loop only 2 times when i=0 and when i=1
ASKER
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)
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)
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.
And to answer a previous question of yours...
(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.
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.
ASKER
I wonder why they are deviding by two
for(int i=0;i<charArray.length/2;i
please advise