I assume that the sample input is something like => love?water!WorLd?H3lle
In the case of -> worldworld234,ELSworldo2? , will the result be 2? or 0?
The error message shows that I am not counting all the instances of "world", although I've already tested this solution locally.
Essentially the code in the while loop goes like:
- Read the character and convert it into a string
- If this character (in string form) is a puunctuation, then check to see if the length of stringbuilder is 5, then, check to see if its String version equals to "world", if not just reinitialize a new StringBuilder.
- If this character is not a punction, then it's still a part of a word, so simply append it to StringBuilder (sb),
Any advice would be greatly appreciated 😊
package com.codegym.task.task19.task1907;
/*
Counting words
*/
import java.io.*;
public class Solution {
private static StringBuilder sb = new StringBuilder();
// private static char[] chars = new char[]{' ', ' ',' ',' ',' '};
private static int result = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String file = br.readLine();
FileReader fr = new FileReader(file);
String punc = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
while(fr.ready()){
String c = Character.toString((char) fr.read());
if(punc.contains(c)){
if(sb.length() == 5){
checkStringBuilder();
}
sb = new StringBuilder();
} else {
sb.append(c);
}
}
checkStringBuilder();
br.close();
fr.close();
System.out.println(result);
// System.out.println(sb.toString());
}
public static void checkStringBuilder(){
String str = sb.toString().toLowerCase().trim();
// System.out.println(str);
if(str.equals("world")){
result++;
}
}
}