From f62d1646c03e4d5413394515995c79755d212804 Mon Sep 17 00:00:00 2001 From: Sergii Konovalov Date: Tue, 24 Sep 2024 20:25:31 +0300 Subject: [PATCH] homework solution --- src/main/java/core/basesyntax/FileWork.java | 37 +++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/core/basesyntax/FileWork.java b/src/main/java/core/basesyntax/FileWork.java index ba2d8396..79ea18c0 100644 --- a/src/main/java/core/basesyntax/FileWork.java +++ b/src/main/java/core/basesyntax/FileWork.java @@ -1,8 +1,41 @@ package core.basesyntax; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; + public class FileWork { public String[] readFromFile(String fileName) { - //write your code here - return null; + char targetLetter = 'w'; + StringBuilder stringBuilder = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + String value; + while ((value = reader.readLine()) != null) { + stringBuilder.append(value).append(" "); + } + } catch (IOException e) { + throw new RuntimeException("Can't read the file", e); + } + String fileContent = stringBuilder.toString().toLowerCase(); + String[] arrayOfWords = fileContent.split("\\s+"); + int count = 0; + for (String word : arrayOfWords) { + if (word.toLowerCase().startsWith(String.valueOf(targetLetter))) { + count++; + } + } + String[] resultArray = new String[count]; + int index = 0; + for (String word : arrayOfWords) { + if (word.toLowerCase().startsWith(String.valueOf(targetLetter))) { + while (word.length() > 0 && !Character.isLetter(word.charAt(word.length() - 1))) { + word = word.substring(0, word.length() - 1); + } + resultArray[index++] = word; + } + } + Arrays.sort(resultArray); + return resultArray; } }