我的任务是读取第一个字符串和第二个字符串中有多少个字符匹配,依此类推。
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++;
}
}
}
输入和输出示例 -
在: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);
}
}
最佳答案
您可以按如下方式进行:
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
关于java - 如何计算字符串中2个字符的匹配次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59115743/