0

I have two Strings,A and B, A has the value of "ABCDE" and B the value of "12345" and I would like to make a for loop that makes the String C, to have the value of "A1B2C3D4E5", the problem is that the value of A and B may vary, A and B can be equal or A greater than B just by one character, only these two options are possible:

if(A.length()>B.length()){
   B=B+"_";
}
int length=A.length()+B.length();
for(int count = 0; count == length;count++){
   C=C+A.charAt(count)+B.charAt(count);
}
System.out.println(C);

But nothing prints out.

1
  • homework? do you know debugger? Commented Nov 19, 2014 at 17:21

3 Answers 3

3

just try like this

    for(int count = 0; count < length/2;count++){
       C=C+A.charAt(count)+B.charAt(count);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is your conditional in the for loop, "count == length". This would mean the for loop runs so long as count is equal to length, i.e. it will not run unless the length is 0 (the initial condition of count).

You could write:

if (A.length() > B.length()) B += "_";
for (int i = 0; i < A.length(); i++) C = C + A.charAt(i) + B.charAt(i);
System.out.println(C);

Comments

0
int max = B.length()
if (A.length() > B.length()){
    max = A.length()
}
String C = "";
for (int i = 0; i < max; i++){
    if (i < A.length){
        C = C + A.charAt(i)
    }
    if (i < B.length){
        C = C + B.charAt(i);
    }
}

This checks to get the maximum length to iterate, and then in the for loop, only adds characters that exist, in an alternating pattern from each string until one string is empty, and then the rest of the other string is appended to the end one character at a time. This allows for this method of concatenation on two strings of any length, not just strings with lengths that differ by 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.