【问题标题】:Java - Get substring from 2nd last occurrence of a character in stringJava - 从字符串中第二次出现的字符获取子字符串
【发布时间】:2020-02-26 09:10:37
【问题描述】:

我的输入:"professions/medical/doctor/"

我想要的输出:"doctor"

我有以下解决方案,但它不是单行的:

String v = "professions/medical/doctor/";
String v1 = v.substring(0, v.length() - 1);
String v2 = v1.substring(v1.lastIndexOf("/")+1, v1.length());
System.out.println(v2);

我怎样才能在单行中达到同样的效果?

【问题讨论】:

  • 您可以使用正则表达式来实现相同的目的。像 \/\w+\/$ 这样的东西会给你匹配。

标签: java string substring indices lastindexof


【解决方案1】:

使用lastIndexOf(str, fromIndex) 变体:

String v2 = v.substring(v.lastIndexOf('/', v.length() - 2) + 1, v.length() - 1);

【讨论】:

  • 我得到这个错误:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 @iluxa
  • 我的错,误解了fromIndex。更新了答案,试试吧
【解决方案2】:

我可能会在这里使用String#split(需要一个或两个行的解决方案):

String v = "professions/medical/doctor/";
String[] parts = v.split("/");
String v2 = parts[parts.length-1];
System.out.println(v2);

如果你知道你想要第三个组件,那么你可以使用:

System.out.println(v.split("/")[2]);

对于真正的单线,String#replaceAll 可能会起作用:

String v = "professions/medical/doctor/";
String v2 = v.replaceAll(".*/([^/]+).*", "$1");
System.out.println(v2);

【讨论】:

  • 我喜欢这里的拆分技术。分成几段,取出你想要的那一段。
  • 我也喜欢拆分。香蕉分裂 - 更是如此。
  • @ScaryWombat 现在停下来!你让我饿了。
猜你喜欢
  • 1970-01-01
  • 2018-02-05
  • 2013-10-02
  • 2017-05-28
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 2014-03-21
相关资源
最近更新 更多