简体   繁体   中英

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

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;
        }
    }
}

您只需要1行:

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

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;
              }       
          }
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM