2010-05-04 255 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")  = "" 
相關問題