2016-06-21 36 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

相关问题