Owen Nel
Owen Nel

Reputation: 417

Java String: Checking for consecutive letters or numbers

Problem: I am playing around in Java and I am trying to count consecutive 'characters' within a string.

Example:

Scanner in = new Scanner(System.in);
int n = in.nextInt();

String binaryString = Integer.toBinaryString(n);

The above code returns a binary string of the integer value entered. If we input the number 5 this will return: 101

I now wish to loop through the String and check if there are any consecutive 1's within the String.

for (int i = 0; i < binaryString.lenth(); i++)
{
    // code comes here...
}

I am not sure how I can check this. I have tried the following:

    for (int i = 0; i < binaryString.length(); i++)
    {
        char charAtPos = binaryString.charAt(i);
        char charAtNextPos = binaryString.charAt(i+1);
        if (charAtPos == '1')
        {
            if (charAtPos == charAtNextPos)
            {
                consecutive += 1;
            }
        }
    }

But this obviously throws an ArrayIndexOutOfBounds as i+1 will produce a number larger than the array length.

Thank you in advance for your answers.

Owen

Upvotes: 0

Views: 3222

Answers (3)

Bohemian
Bohemian

Reputation: 425208

You only need 1 line:

binaryString.split("1(?=1)").length() - 1;

Upvotes: 0

D.Karthikeyan
D.Karthikeyan

Reputation: 118

We can still simplify your code using and operator

  import java.util.Scanner;
  class StackBinary
    {
      public static void main(String args[])
       {
            Scanner in = new Scanner(System.in);
            String n = Integer.toBinaryString(in.nextInt());

            for (int i = 0; i < n.length()-1; i++)
            {
               char charAtPos = n.charAt(i);
               char charAtNextPos = .charAt(i+1);
              if (charAtPos == '1' && charAtNextPos == '1')
              {
                   consecutive+=1;
              }       
          }
       }

Upvotes: 0

Saurabh Kataria
Saurabh Kataria

Reputation: 81

try running the for loop for size one less than the length of the strin

 for (int i = 0; i < (binaryString.length()-1); i++)
{
    char charAtPos = binaryString.charAt(i);
    char charAtNextPos = binaryString.charAt(i+1);
    if (charAtPos == '1')
    {
        if (charAtPos == charAtNextPos)
        {
            consecutive += 1;
        }
    }
}

Upvotes: 1

Related Questions