【问题标题】:Skipping empty indexes in a 2d char[][] array when looping the array for a char value and appending it to a String为 char 值循环数组并将其附加到字符串时跳过 2d char[][] 数组中的空索引
【发布时间】:2020-07-18 15:45:20
【问题描述】:

在循环遍历 2D char[][] 数组时如何跳过所有空索引,以便从所有具有 char 值的索引中构建一个字符串?

在下面的代码中,我使用\0 来表示空索引,并编写了一个条件来将所有不是\0 的索引附加到文本中。这是一个好方法还是有更有效的方法?

StringBuilder text = new StringBuilder();
for (int i = 0; i < row; i++) {
 for (int j = 0; j < col.length(); j++) {
   if (charArray[i][j] != '\0') {
     text.append(charArray[i][j]);
   }
 }
this.newText = text.toString();

【问题讨论】:

    标签: java arrays 2d stringbuilder


    【解决方案1】:

    您需要遍历整个二维数组以找出空元素。

    对于移动二维 A[m][n] 数组,时间复杂度(最佳)为 O(m*n),您正在使用它,因此没有任何其他方法可以降低时间复杂度。

    '\0' 和 ' ' 之间有区别。 `\0' 代表 null 而 ' ' 代表空字符。 您的用例需要省略空字符,因此请使用 ' '

    for (int i = 0; i < row; i++) {
     for (int j = 0; j < col.length(); j++) {
       if (charArray[i][j] != '') {
         text.append(charArray[i][j]);
       }
     }
    this.newText = text.toString();
    

    【讨论】:

    • 嗨。感谢你的回答。我还想知道避免将空索引附加到字符串的最佳方法是否是使用这段代码: if (charArray[i][j] != '\0') { text.append(charArray[ i][j]);
    • '\0' 表示空值。空 char 和 null 之间是有区别的。因此,如果您想省略空值,请使用if(charArray[i][j] != '') text.append(charArray[i][j]);。这不会在文本变量中附加字符。 '\0' 一般用于查找字符的结尾,即 null,而不是空字符。
    【解决方案2】:

    这将迭代 charArray 测试值的所有行和列,并允许不同长度的数组:

    char[][]charArray = new char[][] { new char[] {65, '\0', 66 }
                                     , new char[] {68,69, 70, '\0', 71 }};
    
    
    StringBuilder text = new StringBuilder();
    for (int i = 0; i < charArray.length; i++) {
        char[] theRow = charArray[i];
        for (int j = 0; j < theRow.length; j++) {
          if (theRow[j] != '\0') {
            text.append(theRow[j]);
          }
        }
    }
    String s = text.toString();
    System.out.println("s.length()="+s.length()+" s="+s);
    

    打印:

    s.length()=6 s=ABDEFG
    

    请注意,'' 不是有效字符,可以使用 '\0'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2014-05-27
      • 2021-09-14
      • 2011-08-23
      相关资源
      最近更新 更多