-4

input 10100011

output 10 10 00 11 two word separately.

static String getValue(String x){
    String y = "";
    int getLength = x.length();
    if (getLength % 2 == 0){
        System.out.println("Length : "+getLength/2);
        for (int i = 0; i < getLength/2; i++){

        }
    }
    return y;
}
Mr.deva
  • 3
  • 3
  • 7

3 Answers3

2

This solution uses a StringBuilder1 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.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
2

You can use string operations for this:

for (int i = 0; i < str.length()-1; i+=2){
   System.out.print(str.substring(i, i+2) + " ");
}
if(str.length() % 2 != 0)
    System.out.print(str.substring(str.length()-1));
Kaushal28
  • 5,377
  • 5
  • 41
  • 72
1

As per my understanding, you want to print two digits in string separately.

As per 10 10 00 11 this output,

static String getValue(String x){
    String y = "";
    int getLength = x.length();

        System.out.println("Length : "+getLength/2);
        for (int i = 0; i < getLength; i++){
            if(i%2 == 1) { // this purpose of this check is to make sure this string index starting from 0.
                System.out.println(y[i]+" ") // whenever second digit comes it will print space as well to show seperation.
            } else {
            System.out.println(y[i])
            }
        }

    return y;
}
Hasnain Bukhari
  • 458
  • 2
  • 6
  • 23