Untitled
unknown
plain_text
3 years ago
2.5 kB
6
Indexable
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SwearWords { private static String FILE_PATH = "text.txt"; private static List<String> swearDictionary = Arrays.asList("fuck", "bloody", "cock", "shit", "fucker", "fuckstick", "asshole", "dick", "piss", "cunt"); public static int swearWordCount(String filePath) { Path path = Paths.get(filePath); List<String> outputList = new ArrayList<>(); int swearWordCounter = 0; try { List<String> content = Files.readAllLines(path); for (String row : content) { String newRow = ""; String[] rowWords = row.split(" "); for (String word : rowWords) { String firstLetter = ""; if (word.length() > 1) { if (Character.isUpperCase(word.toCharArray()[0])) { firstLetter += word.toCharArray()[0]; word = word.toLowerCase(); } if (swearDictionary.contains(word)) { word = word.replaceAll(word, ""); swearWordCounter++; } else if (swearDictionary.contains(word.substring(0, word.length() - 1))) { word = word.replaceAll(word.substring(0, word.length() - 1), ""); swearWordCounter++; } } if (word.length() > 0) { if (firstLetter.length() == 0) { newRow += word + " "; } else { newRow += firstLetter + word.substring(1, word.length()) + " "; } } } outputList.add(newRow); } Files.write(path, outputList); } catch (IOException e) { System.out.println("IOError when try reading the file."); e.printStackTrace(); } return swearWordCounter; } public static void main(String[] args) { System.out.println(SwearWords.swearWordCount("C:\\Users\\KerkyPC\\Desktop\\trialexam2\\src\\text")); } }
Editor is loading...