Java 如何获取字符串的最后三个单词?

Java 如何获取字符串的最后三个单词?,java,Java,我有一个包含以下内容的字符串: D:\ptc\Windchill\u 10.0\Windchill\wtCustom\wt\lifecycle\StateRB.rbInfo 我只想得到这一部分: wt\lifecycle\StateRB 我如何才能做到这一点?您可以使用带\delimiter的string tokeniezer,只获取最后三个字符串标记。我希望这条路永远不变 检查上面的链接 例如: String Str = new String("Welcome to Tutorialsp

我有一个包含以下内容的字符串:

D:\ptc\Windchill\u 10.0\Windchill\wtCustom\wt\lifecycle\StateRB.rbInfo

我只想得到这一部分:

wt\lifecycle\StateRB


我如何才能做到这一点?

您可以使用带\delimiter的string tokeniezer,只获取最后三个字符串标记。我希望这条路永远不变

检查上面的链接

例如:

  String Str = new String("Welcome to Tutorialspoint.com");
  System.out.print("Return Value :" );
  System.out.println(Str.substring(10) );

  System.out.print("Return Value :" );
  System.out.println(Str.substring(10, 15) );

您可以简单地将整个路径拆分为多个部分,然后获得所需的部分

String path = "D:\ptc\Windchill_10.0\Windchill\wtCustom\wt\lifecycle\StateRB.rbInfo";
String[] parts = path.split("\\");
parts = Arrays.copyOfRange(parts, parts.length-3, parts.length);
或者,您可以使用循环完成字符串(这似乎更好)

int索引=0,i=0;
堆栈al=新堆栈();
而((index=path.lastIndexOf())=-1&&i<3){
al.push((路径=路径子字符串(索引));
i++;
}
字符串[]部分=(字符串[])al.toArray()//如果没有数组元素
//按照正确的顺序,您可以使用
//Collections.reverse with Arrays.asList
//应用于阵列

这不是最后三个词,您删除了rbinfo。澄清。@ruakh我使用了以下代码:String[]str_array=path.split(“wt”);ArrayList=新建ArrayList();为(inti=0;i@Junuxx-你一定是dropped@gouthami:若要编辑您的问题,请转到。(挑剔)如果没有3个部分会发生什么…:P@user35443-我得到这个异常:线程“main”中的异常java.util.regex.PatternSyntaxException:索引1附近出现意外内部错误\r\n请尝试“\\\\\”或尝试使用pattern.compile(\\”)编译模式,并将其作为split的参数传递,或者使用我的第二个解决方案,正如@MadProgrammer所指出的,这应该更好。我的路径从来都不是常量,上面的路径不是常量
int index = 0, i = 0;
Stack<String> al = new Stack<String>();
while((index = path.lastIndexOf()))!=-1 && i < 3) {
    al.push((path = path.substring(index)));
    i++;
}
String[] parts = (String[])al.toArray(); //if you don't have array elements
                                         // in correct order, you can use 
                                         // Collections.reverse with Arrays.asList 
                                         // applied on array