【问题标题】:Java String Parameters first/last parameterJava字符串参数第一个/最后一个参数
【发布时间】:2023-03-10 00:20:01
【问题描述】:

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

这就是任务:

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

 <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"

提示

  • 如果你按下运行,你会看到所有 System.out.println 的控制台输出

【问题讨论】:

  • 为什么第二个例子输出-1?那里有一个a。为什么第一个示例输出 0?那里没有D
  • 到目前为止你尝试了什么?

标签: java string char


【解决方案1】:
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;
}

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多