Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the size of a char array in Java

Tags:

java

arrays

I'm making a calculator and I have converted a String to a char array using

char[] b = inputString.toCharArray();

(inputString is my String variable)

Because the String is an input I don't know how large the array will be. Is there an inbuilt method that allows you to find the number of elements in the array? Thanks in advance.

like image 434
imulsion Avatar asked Jul 30 '12 18:07

imulsion


2 Answers

You can use b.length to find out how many characters there are.

This is only the number of characters, not indexing, so if you iterate over it with a for loop, remember to write it like this:

for(int i=0;i < b.length; i++)

Note the < (not a <=). It's also important to note that since the array isn't a class, .length isn't a function, so you shouldn't have parenthesis afterward.

like image 120
SomeKittens Avatar answered Oct 13 '22 01:10

SomeKittens


Don't listen to any of these guys, here, try this!

static int length(final char[] b) {
  int n = 0;
  while (true) {
    try {
      int t = b[n++];
    } catch (ArrayIndexOutOfBoundsException ex) {
      break;
    }
  }
  return n;
}

(Just kidding... try b.length.)

like image 20
obataku Avatar answered Oct 12 '22 23:10

obataku