Length of string array?

I am making a function to remove any lines that start with the character # from an array of strings. I am getting an error though. cannot invoke size() on an array of type String[]. This makes sense but it also doesnt. How can i get the number of elements in an array of strings?

for(int i = 0; i < elements.size(); i++)
  {
    if(elements[i].sub(0,1) = "#")
    {
      elements.remove(i);
    }
  }
println(elements);

Answers

  • _vk_vk
    edited November 2013

    elements.length is the size of the array, how many different strings you have.

    elements[i].size() would be the size of the string at position i in your array.

  • Answer ✓

    The size of the array is

    elements.length

    but it won't do you any good because there is an error on line 3 and in line 5 there is no such method remove() for an array.

    This code will do what you want and is easy enough to follow what happens.

    StringList list = new StringList();
    String[] elements = { 
      "123", "#456`", "#789"
    };
    
    for (int i = 0; i < elements.length; i++)
    {
      if (!elements[i].startsWith("#"))
      {
        list.append(elements[i]);
      }
    }
    elements = list.array();
    println(elements);
    
  • edited November 2013

    Arrays, alongside String, Object and all of the 8 wrappers for the corresponding primitive types,
    got some special treatments from the Java language. And among them, arrays got most privileges! ^:)^

    • We don't instantiate arrays calling a constructor using parens, but w/ square brackets []!
    • We don't access its elements by invoking a method, but also using square brackets.
    • And as mentioned by others above, we gotta directly access its length field to know its immutable # of elements!
Sign In or Register to comment.