【问题标题】:How could I separate this string by 2 character increments?如何将此字符串分隔 2 个字符增量?
【发布时间】:2020-11-23 19:11:27
【问题描述】:

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

BB

GB

GB

背景

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

【问题讨论】:

  • 您是什么意思“将每 2 个字符 分配给它们的变量”?
  • 你可能想看看String.substring()
  • @Spectric 例如 numBG 需要在字符串中每次出现“BG”时增加 1
  • @RIVERMAN2010 谢谢,我用了 token = token.substring(0);在每个循环之后

标签: java string printing delimiter next


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 2011-03-06
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多