2016-06-21 89 views
-3
class temp 
{ 
    public static void main(String []args) 
    { 
     String [] arp = new String [] {"Sarah is a good girl","Sarah is a bad girl"} ;// I only want to print "good" from this array and not the entire string in the below println statement. 

     System.out.println(arp[0]);//this will print the entire string on element[0] while i only want to print "good" from that string. 
    } 
} 

如果這個問題解決了,那麼我的上一個問題也將被解決。如何僅打印字符串數組中的特定細節?

+1

查找到'substring' – Idos

+0

'的System.out.println( 「好」)'?似乎你需要在你的問題上更具體。你是否想在「莎拉是一個X女孩」或甚至「Y是一個X女孩/男孩」中找出X? –

+0

@Samon Fischer謝謝你的回答,但是這個字符串只是一個例子,在那個地方可能有任何東西不僅僅是好的。我想要某種技術或方法,我可以打印出「好」所在的第四部分。 「這是一個很好的房子」 我只打印第五個單詞「House」或第四個單詞「fine」。 這是可能的,我問? – user25142514

回答

0

只需使用一個if語句和String.contains

String[] strs = ...; 
for (int i = 0; i < strs.length; i++) { 
    if (strs[i].contains("good")) System.out.println("good"); 
} 
+0

謝謝...好用的方法...它將解決我的問題... – user25142514

0

你也可以使用字符串分割()函數。

例子:

String [] arp = new String [] {"Sarah is a good girl","Sarah is a bad girl"} ; 

    for (int i = 0; i < arp.length; i++) { 
    String data = arp[i]; 
    String[] ex = data.split(" "); // You trim to remove leading and trailing spaces here 
    System.out.println(ex[0]); //prints Sarah 
    System.out.println(ex[1]); //prints is 
    System.out.println(ex[2]); //prints a 
    System.out.println(ex[3]); //prints good 
    System.out.println(ex[4]); //prints girl 
} 
0

它將很好地工作。

class temp{ 
    public static void main(String []args){ 
     String arp[] ="Sarah is a good girl","Sarah is a bad girl" ; 
     System.out.println(arp[3]); 
    } 
} 

https://ideone.com/5mDnZS

+0

哇...令人印象深刻。謝謝 – user25142514

相關問題