[英]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. 问题:我正在用Java玩耍,并且试图计算字符串中的连续“字符”。
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
如果输入数字5,则返回:101
I now wish to loop through the String and check if there are any consecutive 1's within the String. 我现在希望遍历字符串,并检查字符串中是否有任何连续的1。
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. 但这显然会引发ArrayIndexOutOfBounds,因为
i+1
会产生一个比数组长度大的数字。
Thank you in advance for your answers. 预先感谢您的回答。
Owen 欧文
try running the for loop for size one less than the length of the strin 尝试运行for循环,使其大小小于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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.