package tools.string;

public class StringSearcher {
	public static String searchData(String text, String startword,
			String[] stopwords) {
		
		String data = "";
		boolean found = false;
		int i = 0;
		String lowercaseText = text.toLowerCase();
		String lowercaseStartword = startword.toLowerCase();

		String[] lowercaseStopwords = new String[stopwords.length];

		for (int j = 0; j < stopwords.length; j++) {
			lowercaseStopwords[j] = stopwords[j].toLowerCase();
		}

		while (i < text.length() - startword.length() + 1 && !found) {
			if (lowercaseText.startsWith(lowercaseStartword, i)) {
				String lcReminder = lowercaseText.substring(i
						+ startword.length());

				int j = 0;
				while (j < lcReminder.length() && !found) {
					for (int k = 0; k < stopwords.length; k++) {
						if (lcReminder.startsWith(lowercaseStopwords[k], j)) {
							found = true;
							data = text.substring(i + startword.length(), i + startword.length() + j);
							data = deleteTrailingAndEndSpaces(data);
						}
					}
					j++;
				}
			}
			i++;
		}

		return data;
	}

	public static String deleteTrailingAndEndSpaces(String s) {
		while (s.length() > 0 && isSpace(s.charAt(0))) {
			s = s.substring(1);
		}

		while (s.length() > 0 && isSpace(s.charAt(s.length() - 1))) {
			s = s.substring(0, s.length() - 1);
		}

		return s;
	}

	public static boolean isSpace(char c) {
		return (c == '\n' || c == '\r' || c == '\t' || c == ' ');
	}

}
