2016-07-14 23 views
-2

我需要从字符串变量中删除像猫和鱼这样的字符串值。 我做了一些示例Java代码来删除字符串值。使用Java删除字符串值

public static void deleteAccNode(String refId){ 
    String refId [] = {"Fish","Dog","Dolphins","rowboat","Fish","sailor","Cat","cats","Cat","Fish", 
     "Fish","Tree","Fishes","Cat","Cat","CAT","Cat"}; 

     try { 
      System.out.println("GeneralLength"+refId.length); 
      for (int n = refId.length; n <= 1;){ 
      if(refId.equals("Cat")){ 
       System.out.println("cat : :"+refId); 
       How to remove the String value?remove("Cat"); 
       }else if(refId.equals("Fish")){ 
        System.out.println("Fish : :"+refId); 
        How to remove the String value?remove("Fish"); 
       } 
      n--; 
      } 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

需要的输出:狗,海豚,划艇,水手,猫,树,鱼,CAT 但是,电流输出:NullPointerException异常

+2

所以...什么阻止你? – Stultuske

+0

究竟是什么问题? –

+1

“鱼”“狗”“海豚”“划艇”“鱼”“水手”“猫”“猫”“猫”“鱼” +“鱼” “树”,“鱼”,“猫”,“猫”,“猫”,“猫”;'从未见过这样的事情。我不认为它编译? – ifly6

回答

1

这只是一种方式,是有很多,你可以刚刚google了这个。

String[] stringArray = { "Cat", "Fish", "CatFish", "Elephant" }; 
    final List<String> newArrayList = new ArrayList<>(); 
    for (final String string : stringArray) 
    { 
    if (!(string.equals("Cat") || string.equals("Fish"))) 
    { 
     newArrayList.add(string); 
    } 
    } 

    stringArray = (String[]) newArrayList.toArray();