我怎样才能将这个字符串以 2 个字符的增量分隔?

How could I separate this string by 2 character increments?

没有分隔符,字符串本身来自格式如下的文件:

BB

GB

GB

BG

GG

GB

GB

GB

GB

GG

使用以下代码后,我得到了 BBGBGBBGGGGBGBGBGBGG,正如 token = in.nextLine( ) 之后的打印语句所打印的那样;我对这个程序的目标是将每 2 个字符分配给它们的变量并递增它们以获得计数。我只是不知道如何正确地增加和分配它们。感谢任何帮助。

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
   public static void main (String args[]) throws IOException {
    //variables defined
    int numGB = 0;
    int numBG = 0;
    int numGG = 0;
    int numBB = 0;
    int totalNum = 0;
    double probBG;
    double probGG;
    double probBB;
    String token ="";
    int spaceDeleter = 0;
    int token2Sub = 0;
    
    File fileName = new File ("test1.txt"); 
    
    Scanner in = new Scanner(fileName); //scans file
    
    System.out.println("Composition statistics for families with two children");
    while(in.hasNextLine())
    {
        token = in.nextLine( ); //recives token from scanner
        System.out.print(token);
        if(token.equals("GB"))
        {
        numGB = numGB + 1;
        }
        else if(token.equals("BG"))
        {
        numBG = numBG + 1;
        }
        else if(token.equals("GG"))
        {
        numGG = numGG + 1;
        }
        else if(token.equals("BB"))
        {
        numBB = numBB + 1;
        }
        else if(token.equals(""))
        {
        spaceDeleter =+ 1; //tried to delete space to no avial
        }
        else 
        {
        System.out.println("Data reading error");
        }
    }

最简单的方法是使用地图。要拆分字符串,请将每两个字符替换为后跟一些未使用的字符的字符串。然后拆分这些字符。剩下的就是流式传输字符对数组并进行频率计数。

String s = "BBGBGBBGGGGBGBGBGBGG";
Map<String, Long> count =
        Arrays.stream(s.replaceAll("..", "[=10=]#").split("#"))
                .collect(Collectors.groupingBy(a -> a,
                        Collectors.counting()));

count.forEach((k,v)-> System.out.println(k + " -> " + v));

版画

GG -> 2
BB -> 1
BG -> 1
GB -> 6