Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework solution #1334

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions src/main/java/core/basesyntax/FileWork.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
Loading