【问题标题】:Copy String array and remove empty strings复制字符串数组并删除空字符串
【发布时间】:2012-03-25 08:38:36
【问题描述】:

我想消除我的String 数组中的空元素。这是我迄今为止尝试过的:

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i] == "")
    {

    }
    else
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].equals(""))
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].isEmpty())
    {
        xml[i] = str[i]; 
    }
}
String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i].isEmpty() == false)
    {
        xml[i] = str[i]; 
    }
}

无论我尝试哪一个,它总是复制所有值。我查了locals,很明显String数组里面有空数组。

【问题讨论】:

  • 你确定其中没有空格?
  • 顺便说一句,您确实意识到,只要您不复制字符串,就会在xml[i] 留下null,对吧?对两个数组使用相同索引的后果之一...
  • 你确定它们是空的(而不仅仅是包含空白字符的字符串)?也许在进行比较之前尝试修剪(str[i].trim())?请注意,== 不是您想要的,但其他两个应该可以工作。
  • 是的...我很确定...我会发布一张图片..
  • @BlueMonster:如果您要复制到数组中,则不会 - 因为您将较少的元素复制到相同大小的数组中,所以那里几乎总是会有空值,除非您检查一次并计算有多少字符串不为空,然后在复制之前将xml 设为该大小。 (如果你这样做,你可以拥有另一个 int,它是 xml 的索引,并且每当你复制一个字符串时都会撞到它。)但更好的是使用 ArrayList,如下所述。

标签: java arrays string


【解决方案1】:

试试这个,

b = Arrays.copyOf(a, a.length);

或者

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

或者

b = a.clone();

【讨论】:

  • 虽然这段代码可能有助于解决问题,但它并没有解释为什么和/或如何回答问题。提供这种额外的背景将显着提高其长期教育价值。请edit您的答案添加解释,包括适用的限制和假设。
【解决方案2】:

您正在复制相同长度的数组并使用相同的索引。长度总是一样的。

List<String> nonBlank = new ArrayList<String>();
for(String s: str) {
    if (!s.trim().isEmpty()) {
        nonBlank.add(s);
    }
}
// nonBlank will have all the elements which contain some characters.
String[] strArr = (String[]) nonBlank.toArray( new String[nonBlank.size()] );

【讨论】:

  • 嗯,我使用的是字符串数组,而不是字符串列表。无论如何,谢谢
  • hmm,添加了一行来将一个转换为另一个。 ;)
【解决方案3】:
String str[] = {"Hello","Hi","","","Happy","","Hmm"};
    int count = 0;// Thisreprents the number of empty strings in the array str
    String[] xml = new String[str.length]; 
    for(int i = 0,j=0; i <= str.length -1; i++)
    {
        if(str[i].equals(""))
        {
            count++;
        }
        else
        {
            xml[j] = str[i];j++; 
        }
    }
    String a[] = Arrays.copyOfRange(xml, 0, xml.length-count);//s is the target array made by copieng the non-null values of xml
    for(String s:a){
        System.out.println(s);
    }

注意:这可能不是一个有效的解决方案,但它会根据您的要求给出结果

【讨论】:

    【解决方案4】:

    这只是一个替代解决方案,因为您不想要ListArray。 阅读代码中的cmets,逻辑清晰。

    int i,j=0,cnt=0;
    
    //The below for loop is used to calculate the length of the xml array which
    //shouldn't have any empty strings.
    
    for(i=0;i<str.length;i++)
    if(!isEmpty(str[i])
    cnt++;
    
    //Creation of the xml array with proper size(cnt) and initialising i=0 for further use
    String xml[]=new String[cnt];
    i=0;
    
    //Simply copying into the xml array if str[i] is not empty.Notice xml[j] not xml[i]
    while(i<str.length)
    {
    if(!isEmpty(str[i]))
    {
    xml[j]=str[i];
    i++;
    j++;
    }
    else
    i++;
    }
    

    这应该可以完成工作。 另外,我建议不要使用数组的第 0 位,因为它会为 .length 函数造成混乱。这只是我的观点。如果你觉得舒服,继续! :D

    【讨论】:

      【解决方案5】:

      如果您正在寻找高性能的解决方案,我认为这是最好的解决方案。否则,如果您的输入数组不是那么大,我会使用类似于 Peter Lawrey 的解决方案,因此它使您的代码易于理解。

      使用此解决方案,您只需循环一个输入数组,如果您不再需要输入数组,您可以避免使用preserveInput = false 调用filterBlankLines 的一个数组副本。

      public class CopyingStringArrayIntoNewStringArray {
      
      
      public static void main(String[] args) {
      
          String[] str =  { "", "1", "", null, "2", "   ", "3", "" };
      
          System.out.println("\nBefore:");
          printArrays(str);
      
          String[] xml = filterBlankLines(str, true);
      
          System.out.println("\nAfter:");
          printArrays(xml);
      
      }
      
      private static String[] filterBlankLines(String input[], boolean preserveInput ) {
      
          String[] str;
          if (preserveInput) {
              str = new String[input.length];
              System.arraycopy(input, 0, str, 0, input.length);
          } else {
              str = input;
          }
      
          // Filter values null, empty or with blank spaces
          int p=0, i=0;
          for (; i < str.length; i++, p++) {
              str[p] = str[i];
              if (str[i] == null || str[i].isEmpty() || (str[i].startsWith(" ") && str[i].trim().isEmpty())) p--;
          }
      
          // Resize the array
          String[] tmp = new String[ p ];
          System.arraycopy(str, 0, tmp, 0, p);
          str = null;
      
          return tmp;
      }
      
      private static void printArrays(String str[]) {
      
          System.out.println( "length " + str.length);
          for (String s : str ) {
              System.out.println(">"+s+"<");
          }
      
      }
      

      }

      输出:

      Before:
      length 8
      ><
      >1<
      ><
      >null<
      >2<
      >   <
      >3<
      ><
      
      After:
      length 3
      >1<
      >2<
      >3<
      

      【讨论】:

        【解决方案6】:

        这是将数组复制到新数组中的最佳且快捷的方法。

        System.arraycopy(srcArray, 0, destArray, 1, destArray.length -1);
        

        【讨论】:

          猜你喜欢
          • 2021-05-29
          • 1970-01-01
          • 1970-01-01
          • 2021-07-17
          • 1970-01-01
          • 2022-11-16
          • 2012-05-09
          • 2016-05-30
          相关资源
          最近更新 更多