2012-06-12 39 views
0

我有論文兩個字符串轉移:比較兩個字符串一個接一個位置

String s1 = "hello"; 
String s2 ="_hello"; 

我想返回true(第二組是由偏移的位置),這樣的字符串時,我對它們進行比較。

其中String應該使用哪種操作方法?任何人都可以給我一個暗示嗎?

+0

這兩個字符串是任何結果? – anoop

+0

爲什麼不只是's2.equals('_'+ s1)'? – Gene

+0

請勿在問號前使用任何標點符號。 – adarshr

回答

3

您可以使用String類的。

String s1 = "hello"; 
String s2 ="_hello"; 

if(s2.contains(s1)) 
    //true 

您還可以使用subString()

s2= s2.subString(1); 
if(s2.equalsIgnoreCase(s1)) 
    //true 

是的,你也可以使用indexOf()

if(s2.indexOf(s1)>-1) 
    //true 
+1

如果它偏移的事實是重要的,那麼也可以考慮在indexOf()的基礎上構建一個測試。 –

0

我沒有編程機器人,所以藉此與一粒鹽,但看看String.indexOf()。我相信Android是基於Java的,所以這應該有所幫助。

2

您應該使用的indexOf方法:

int index=s2.indexOf(s1); 

if(index ==-1) // s1 is not present into s2. 

其他指數是第一個字符的索引S2匹配S1。例如,在情況下:

String s1 = "hello"; String s2 ="_hello"; 

索引將爲1