【问题标题】:Java substring from right-hand direction, until a specific character [duplicate]从右手方向开始的Java子字符串,直到特定字符[重复]
【发布时间】:2017-11-16 09:09:28
【问题描述】:

我想从输入字符串中选择特定的子字符串:

String i = "example/test/foo-foo";

如何仅获取子字符串foo-foo 作为新字符串?

预期输出:

String newString = "foo-foo";

【问题讨论】:

  • 你有看过String提供的方法吗?
  • int index = i.lastIndexOf("/");字符串名称= i.substring(index + 1);
  • String i = "example/test/foo-foo"; String[] temp = i.split("/"); System.out.println(temp[temp.length-1]);

标签: java string substring


【解决方案1】:

最好的方法是通过一个实用程序类,因为我们可以用这种方法重用代码。此外,可以处理一些极端情况以避免运行时异常。

public class StringUtils {
    public static final String EMPTY = "";

    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        }
        if (isEmpty(separator)) {
            return EMPTY;
        }
        int pos = str.lastIndexOf(separator);
        if (pos == -1 || pos == (str.length() - separator.length())) {
            return EMPTY;
        }
        return str.substring(pos + separator.length());
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

然后使用创建您的newString

String newString = StringUtils.substringAfterLast(i, "/");

【讨论】:

    【解决方案2】:

    有很多选项可以解决这个问题。例如通过正则表达式搜索/替换或 String 类的子字符串方法。

    正则表达式方法:

    Optional<String> resultA = Optional.of(string.replaceAll("^.*/([^/]+)$", "$1"));
    

    子串方法:

    int start = string.lastIndexOf('/');
    Optional<String> resultB = Optional.of(start > 0 && start + 1 < string.length() ? string.substring(start) : null);
    

    顺便说一句,stackoverflow 上有很多针对这个问题的更详细的解决方案,所以最好通过彻底的 stackoverflow 搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多