This solution uses a StringBuilder
1 to append the character to the string being built.
The for loop starts at index 0. In the body of the for loop, it gets the character at index i
and i + 1
and appends to the current builder along with a space. On each iteration, i
gets incremented by two.
StringBuilder builder = new StringBuilder();
if (getLength % 2 == 0){
System.out.println("Length : "+getLength/2);
for (int i = 0; i < x.length(); i += 2){
builder.append(x.charAt(i))
.append(x.charAt(i + 1))
.append(" ");
}
}
return builder.toString();
1The reason for using a StringBuilder is for performance benefits. Read more about this here.