如何计算字符串中找到的2个字符的匹配数?

时间:2019-11-30 11:31:55

标签: java for-loop while-loop

我的任务是读取第一个字符串和第二个字符串等等匹配的字符。

for循环检查所有字符串 但是在while循环内部,直到字符串的字符不等于'|';

  for(int i = 0;i<blobs.length();i++){
       while(blobs.charAt(i)=='|'){
    if(blobs.charAt(i)==pattern.charAt(0) && blobs.charAt(i+1)==pattern.charAt(1)){
      a++;


        }
       }
     }

输入和输出示例-

in:bc; bcdefbcbebc | abcdebcfgsdf | cbdbesfbcy | 1bcdef23423bc32

输出:3 | 2 | 1 | 2 | 8

如何计数直到'|'并重新开始计数?

阅读器

public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
String line;
while ((line = in.readLine()) != null) {
  String[] splittedInput = line.split(";");
  String pattern = splittedInput[0];
  String blobs = splittedInput[1];
  Main.doSomething(pattern, blobs);
   }
 }

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExTest {
    public static void main(String args[]) {
        String str="bcdefbcbebc|abcdebcfgsdf|cbdbesfbcy|1bcdef23423bc32";
        String searchStr="bc";
        String []substrs=str.split("\\|"); //Split the input String at each '|'
        StringBuilder sb=new StringBuilder();
        Pattern pattern;
        Matcher matcher;
        int numberOfMatches;
        int sum=0;
        for(String s:substrs) {
            pattern=Pattern.compile(searchStr);
            matcher = pattern.matcher(s);
            numberOfMatches=0;        
            while (matcher.find()) {
                numberOfMatches++;
            }
            sb.append(String.valueOf(numberOfMatches)+"|");
            sum+=numberOfMatches;
        }
        sb.append(String.valueOf(sum));
        String out=sb.toString();
        System.out.println(out);
    }
}

输出:

3|2|1|2|8

答案 1 :(得分:0)

我认为这会帮助您,将其转换为方法:

public static void main(String[] args) {
    String value = "bcdefbcbebc|abcdebcfgsdf|cbdbesfbcy|1bcdef23423bc32";
    //3|2|1|2|8
    String[] splited = value.split("\\|");
    String toFind = "bc";
    String out = "";

    int total = 0;
    for(String s: splited) {
        int subTotal = 0;
        while(s.contains(toFind)) {
            s = s.replaceFirst(toFind, "");
            subTotal++;
        }
        total += subTotal;

        out += subTotal + "|";
    }

    out += total;
    System.out.println(out);
}