Reputation: 31
My task is to read how many characters match in first string and in second string and so on.
for loop checks all the string but inside while loop works until character of string not equal to '|';
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++;
}
}
}
Example of inputs and output -
in: bc;bcdefbcbebc|abcdebcfgsdf|cbdbesfbcy|1bcdef23423bc32
out: 3|2|1|2|8
How to count until ' |' and start count again ?
Reader
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);
}
}
Upvotes: 1
Views: 86
Reputation: 79445
You can do it as follows:
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);
}
}
Output:
3|2|1|2|8
Upvotes: 2
Reputation: 199
I think this will help you, transform it in methods:
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);
}
Upvotes: 0