【问题标题】:Check for a Substring after a particular occurrence of string which is separated by dots在以点分隔的特定字符串出现后检查子字符串
【发布时间】:2021-11-17 15:17:08
【问题描述】:

我有一个带点的字符串。我想在单词出现后得到一个特定的子字符串

实体

例如

String givenStr = "com.web.rit.entity.TestName.create";
output - TestName

String givenStr = "com.web.rit.entity.TestName2.update";
output - TestName2

如上所述,我必须从给定字符串中提取字符串 entity 之后的子字符串。有人可以帮忙吗? (我是用java来做的)。

【问题讨论】:

  • 你尝试了什么?你可以使用replace 方法?
  • 嗨@Elikill58,我想我会用点来分割它,这会给我一个字符串数组,然后在数组中运行一个循环来检查“实体”字的出现,然后取数组中的下一个字符串。
  • 是的,抱歉,我不太了解您的问题。我在写东西

标签: java string substring


【解决方案1】:

您可以使用 2 个拆分。

String word = givenStr.split("entity.")[1].split("\\.")[0];

说明:

假设给定的Str是“com.web.rit.entity.TestName.create”

givenStr.split("entity.")[1] // Get the sentence after the entity.

“TestName.create”

split("\\.")[0] // Get the string before the '.'

测试名称

【讨论】:

    【解决方案2】:

    你可以这样做:

    String givenStr = "com.web.rit.entity.TestName.create"; // begin str
    String wording = "entity"; // looking for begin
    String[] splitted = givenStr.split("\\."); // get all args
    for(int i = 0; i < splitted.length; i++) {
        if(splitted[i].equalsIgnoreCase(wording)) { // checking if it's what is required
            System.out.println("Output: " + splitted[i + 1]); // should not be the last item, else you will get error. You can add if arg before to fix it
            return;
       }
    }
    

    【讨论】:

      【解决方案3】:

      这是一个流解决方案(Java 9 最低要求):

      Optional<String> value = Arrays
           .stream("com.web.rit.entity.TestName.create".split("\\."))
           .dropWhile(s -> !s.equals("entity"))
           .skip(1)
           .findFirst();
      
      System.out.println(value.orElse("not found"));
      

      【讨论】:

        猜你喜欢
        • 2014-12-04
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-08
        • 2017-02-23
        • 2020-12-06
        • 2017-04-29
        • 2015-08-31
        相关资源
        最近更新 更多