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.
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With