GP92
GP92

Reputation: 435

Two variables initialization at once in for loop

I want to write a code for reversing of string.

I know there are many methods for it. However, I want to try using Arrays. But I am having problem with the output.

Following is my code:

package practice_package;

public class Practice_Class {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s1 = "Jeevan";
    char[] a = s1.toCharArray();
    String s2 = "satyasahithi";
    char[] b = s2.toCharArray();
    String rs1 = new String(reverse(a));
    System.out.println("The reverse of '" + s1 + "' is: '" + rs1 + "'");
    String rs2 = new String(reverse(b));
    System.out.println("The reverse of '" + s2 + "' is: '" + rs2 + "'");

}
public static char[] reverse(char[] args) {
    char[] r = args;
    int i,j;
    for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
        r[j]= args[i]; 
    }
    System.out.println(r);
    return r;
}
}

And my output is:

navvan
The reverse of 'Jeevan' is: 'navvan'
ihtihaahithi
The reverse of 'satyasahithi' is: 'ihtihaahithi'

As you can see, only the first half of the string is being reversed while the second half remains as it is. What's the wrong in the code. Can I initialize two variables at once in 'for' loop like that. Where am I missing the logic?

Upvotes: 0

Views: 133

Answers (3)

Anjo
Anjo

Reputation: 267

The logic inside your for loop. Lets consider the first iteration where i points to 5 (in case of string Jeevan) and j points to 0. When you say r[j]= args[i] J will be replaces with n and you lose the character J. This is the part where your logic went wrong. As a solution either you can take another array and store as given below

public static char[] reverse(char[] args) {
char[] r = new char[args.length];
int i,j;
for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
    r[j]= args[i]; 
}
System.out.println(r);
return r;
}

or as nr4bt suggested above.

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

Use StringBuffer.reverse()

String s1 = "Jeevan";
StringBuffer a = new StringBuffer(s1);
System.out.println(a.reverse());

Upvotes: 0

Nathua
Nathua

Reputation: 8826

When you assign last to first, you lose the char, you should keep it in temporary and assign to other.

for(i=args.length-1,j=0; i>=0 && j<args.length/2; i--, j++) {
    char t = r[j];
    r[j]= r[i];
    r[i] = t;
}

Upvotes: 1

Related Questions