2010-05-04 194 views
2

的子串在Java中,我们有indexOflastIndexOf。有什么像lastSubstring?它应该像:最后一个字符串

"aaple".lastSubstring(0, 1) = "e"; 
+1

犯错,什么'0'和'1'代表什么?你的意思是'e'被退回? – 2010-05-04 21:02:22

+0

'indexOf'和'lastIndexOf'都带一个字符串,并在没有主字符串的情况下找到它,返回该位置。你似乎正在描述相反的情况;你想有一个版本的'子()'的从端,而不是一开始 – 2010-05-04 21:06:42

回答

11

不是在标准的Java API,但是......

阿帕奇百科全书有很多的StringUtils的便利的字符串辅助方法

...包括 StringUtils.right( “苹果”,1)

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#right(java.lang.String,%20int)

只是抓住公地lang.jar的副本从commons.apache.org

+0

很棒的发现。谁写了commons-lang? – fastcodejava 2010-05-06 06:04:28

+1

很多人! http://commons.apache.org/proper/commons-lang/team-list.html – laher 2013-04-07 22:35:58

0

那不是仅仅是

String string = "aaple"; 
string.subString(string.length() - 1, string.length()); 

+4

计算那不是仅仅是'string.subString(string.length减() - 1);'? – 2010-05-04 21:05:55

0

您可以使用string.length减()和string.length减() - 1

-1

我不知道那种对口到substring()的,但它是不是真的有必要。你不能有效地找到使用indexOf()给定值的最后一个索引,所以lastIndexOf()是必要的。为了得到你想要做的事lastSubstring(),你可以有效地使用substring()

String str = "aaple"; 
str.substring(str.length() - 2, str.length() - 1).equals("e"); 

那么,有没有真正需要任何lastSubstring()

+0

's.substring(...)==“e”**总是**返回false! – 2010-05-04 21:09:55

+0

那么,不*总是*(JVM可以重用字符串,但它不必),但你是对的。这不是做正确的方式 - 我还没有被使用的Java不够最近... – 2010-05-04 21:11:40

+0

是的,总是(至少对于所有JVM的我用过)。 'substring(...)'创建一个新的字符串,所以'=='将总是返回false。只有.java文件中的字符串文字被合并并重新使用。片段“String a =”foo“的布尔值x;字符串b =“foo”;布尔值x = a == b;'将会是'true'。 – 2010-05-04 21:17:06

3

归纳其他的反应,可以实现lastSubstring如下:

s.substring(s.length()-endIndex,s.length()-beginIndex); 
+0

这个实现的一个好处是它运行在O(1)时间。 – 2010-05-04 21:22:37

0

对于那些希望得到一个子后,一些结束符,例如解析file.txt/some/directory/structure/file.txt

我发现这是很有帮助:StringUtils.substringAfterLast

public static String substringAfterLast(String str, 
             String separator) 
Gets the substring after the last occurrence of a separator. The separator is not returned. 
A null string input will return null. An empty ("") string input will return the empty string. An empty or null separator will return the empty string if the input string is not null. 
If nothing is found, the empty string is returned. 
     StringUtils.substringAfterLast(null, *)  = null 
     StringUtils.substringAfterLast("", *)  = "" 
     StringUtils.substringAfterLast(*, "")  = "" 
     StringUtils.substringAfterLast(*, null)  = "" 
     StringUtils.substringAfterLast("abc", "a") = "bc" 
     StringUtils.substringAfterLast("abcba", "b") = "a" 
     StringUtils.substringAfterLast("abc", "c") = "" 
     StringUtils.substringAfterLast("a", "a")  = "" 
     StringUtils.substringAfterLast("a", "z")  = "" 
相关问题