Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

public class Main {
    private static List<String> KEYWORDS = Arrays.asList("OR", "AND");

    public static List<String> parse(String input) {
        List<String> term = new ArrayList<>();
        for (String part : input.replace('"', ' ').split("\\s+")) {
            if (part.isEmpty()) {
                continue;
            }
            final String cleaned = clean(part);
            if (isKeyword(cleaned) || cleaned.contains("*")) {
                term.add(part);
            } else if (!cleaned.isEmpty()) {
                term.add(cleaned);
            }
        }
        return term;
    }

    private static String clean(String input) {
        int begin = getStartIndex(input);
        int end = getEndIndex(input);
        if (begin > end) {
            return "";
        } else {
            return input.substring(begin, end + 1);
        }
    }

    static boolean isKeyword(String term) {
        return KEYWORDS.contains(term.toUpperCase(Locale.ENGLISH));
    }

    private static int getStartIndex(String term) {
        int length = term.length();
        int index = 0;
        while (term.charAt(index) == '*') {
            ++index;
            if (index >= length) {
                break;
            }
        }
        return index;
    }

    private static int getEndIndex(String term) {
        int index = term.length() - 1;
        while (term.charAt(index) == '*') {
            --index;
            if (index < 0) {
                break;
            }
        }
        return index;
    }
}