codeFlowType:
codeWrite
codeFlowLang:
Java
Прочитать текст из файла, и написать функцию, которая считает количество вхождений некоторой строки в этот текст без учета регистра символов • Использовать цикл и indexOf, который принимает начальный индекс, с которого искать
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String searchText = "some text";
try {
int count = countOccurrences(filePath, searchText);
System.out.println("The text \"" + searchText + "\" was found " + count + " times in the file.");
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
public static int countOccurrences(String filePath, String searchText) throws IOException {
int count = 0;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
count += countOccurrencesInLine(line, searchText);
}
reader.close();
return count;
}
public static int countOccurrencesInLine(String line, String searchText) {
int count = 0;
int index = -1;
while ((index = line.toLowerCase().indexOf(searchText.toLowerCase(), index + 1)) != -1) {
count++;
}
return count;
}
}