【问题标题】:How to print only specific detail from String array?如何仅打印字符串数组中的特定细节?
【发布时间】:2016-10-23 01:14:50
【问题描述】:
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.
    }
}

如果这个问题解决了,那么我之前的问题也将解决。

【问题讨论】:

  • 查看substring
  • System.out.println("good")?似乎你需要在你的问题更具体。您是否想在“Sarah is a X girl”甚至“Y is a X {girl/boy}”中找出 X?
  • @Samon Fischer 感谢您的回答,但这个字符串只是一个例子,那个地方可能有任何东西不仅仅是好的。我想要某种技术或方法,我可以打印“好”所在的第四部分。 “This is a fine House” 我只想打印第五个单词的“House”或第四个单词的“fine”。这可能是我要问的吗?
  • @Idos 谢谢,这似乎是我感兴趣的事情

标签: java arrays string printing display


【解决方案1】:

只需使用 if 语句和 String.contains

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

【讨论】:

    【解决方案2】:

    它会正常工作的。

    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

    【讨论】:

    • 哇...令人印象深刻。谢谢
    【解决方案3】:

    你也可以使用String split()函数。

    例子:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多