Java字符串参数first / last参数

时间:2018-11-04 17:07:10

标签: java string char

我正在学习,找不到以下任务的解决方案:

这就是任务:

编写一个函数,该函数获取作为字符串参数传递的任务。我们只限于搜索文本。每个任务的结构如下:

 <TASK> <WHAT> <TEXT>

您应该可以搜索第一个和最后一个单词或字母:

 <TASK> = "FIND (FIRST | LAST) (CHAR | WORD)"

输出应始终是搜索开始的位置,否则为-1。

示例:

 "FIND FIRST CHAR D This is a text" → Output: "0"
 "FIND FIRST CHAR a This is a text" → Output: "-1"
 "FIND FIRST CHAR s This is a text" → Output: "3"
 "FIND LAST CHAR t This is a text" → Output: "16"
 "FIND FIRST WORD is This is a text" → Edition: "5"
 "FIND LAST WORD is This is a text" → Output: "5"

提示

  • 如果按Run,您将看到所有System.out.println的控制台输出

1 个答案:

答案 0 :(得分:0)

private static final Pattern PATTERN = Pattern.compile("FIND\\s+(?<pos>FIRST|LAST)\\s+(?<unit>CHAR|WORD)\\s+(?<what>\\S+)\\s+(?<text>.+)");

public static int find(String str) {
    Matcher matcher = PATTERN.matcher(str);

    if (!matcher.matches())
        return -1;

    String pos = matcher.group("pos");
    String unit = matcher.group("unit");
    String what = matcher.group("what");
    String text = matcher.group("text");
    boolean first = "FIRST".equals(pos);

    if ("CHAR".equals(unit))
        return first ? text.indexOf(what) : text.lastIndexOf(what);

    if ("WORD".equals(unit)) {
        Matcher match = Pattern.compile("\\b" + what + "\\b").matcher(text);
        int offs = -1;

        while (match.find()) {
            offs = match.start();

            if (first)
                break;
        }

        return offs;
    }

    return -1;
}