Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package task;
- import java.io.*;
- class SearchPhrase {
- // walk to root way
- public void walk(String path) throws IOException {
- File root = new File(path);
- File[] list = root.listFiles();
- for (File titleName : list) {
- if (titleName.isDirectory()) {
- walk(titleName.getAbsolutePath());
- // System.out.println( "Dir:" + titleName.getAbsoluteFile() );
- } else {
- System.out.println("File:" + titleName.getAbsoluteFile());
- }
- }
- }
- // Read file as one line
- public static String read(String fileName) {
- StringBuilder strBuider = new StringBuilder();
- try {
- BufferedReader in = new BufferedReader(new FileReader(new File(
- fileName).getAbsoluteFile()));
- String strInput;
- while ((strInput = in.readLine()) != null) {
- strBuider.append(strInput);
- strBuider.append("\n");
- }
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return strBuider.toString();
- }
- public static int searchPhrase(String fileName, String what) {
- int n = fileName.length(); // Длина строки, в которой происходит поиск
- int m = what.length(); // Длина подстроки
- // Формирование таблицы сдвигов
- int[] table = new int[m];
- table[0] = 0;
- int shift = 0;
- for (int q = 1; q < m; q++) {
- while (shift > 0 && what.charAt(shift) != what.charAt(q)) {
- shift = table[shift - 1];
- }
- if (what.charAt(shift) == what.charAt(q))
- shift++;
- table[q] = shift;
- }
- // Поиск с использованием таблицы сдвигов
- shift = 0;
- for (int i = 0; i < n; i++) {
- while (shift > 0 && what.charAt(shift) != fileName.charAt(i)) {
- shift = table[shift - 1];
- }
- if (what.charAt(shift) == fileName.charAt(i))
- shift++;
- if (shift == m)
- return i - m + 1; // подстрока найдена
- }
- return -1; // подстрока не найдена
- }
- /**
- * Тестовая процедура: запускает алгоритм и выводит результат его работы.
- *
- * @param args
- */
- public static void main(String[] args) {
- SearchPhrase example = new SearchPhrase();
- String file = read("program test.txt");
- int ndx = example.searchPhrase(file, "программист");
- if (ndx >= 0) {
- System.out.println("Index found: " + ndx);
- } else {
- System.out.println("Substring not found");
- }
- try {
- example.walk("C:\\Documents and Settings\\User\\Java Hangman\\Java\\Anton");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement