如何以 2 个字符的增量分隔此字符串?

How could I separate this string by 2 character increments?

提问人:RideTheLightning343 提问时间:11/24/2020 最后编辑:JonasRideTheLightning343 更新时间:5/12/2023 访问量:83

问:

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

BB系列

国标

国标

BG公司

GG系列

国标

国标

国标

国标

GG系列

使用以下代码后,我留下了 BBGBGBBGGGGBGBGBGBGG,从后面的 print 语句打印出来;我对这个程序的目标是将每 2 个字符分配给它们的变量并递增它们以获得计数。我只是不知道如何正确增加和分配它们。任何帮助都是值得赞赏的。token = in.nextLine( )

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");
        }
    }
爪哇岛 字符串 java.util.scanner 定界符

评论

1赞 Spectric 11/24/2020
“将每 2 个字符分配给他们的变量”是什么意思?

答:

0赞 WJS 11/24/2020 #1

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

String s = "BBGBGBBGGGGBGBGBGBGG";
Map<String, Long> count =
        Arrays.stream(s.replaceAll("..", "$0#").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