I know there are various inbuilt functions, using which we can count string length like lastIndexOf()
, by converting a string into a char array and counting iteration. There is a way in C programming for(i = 0; s[i] != '\0'; ++i);
.
how to count string length in java like in C mentioned above.
Update:
Yes, there are these methods String.length()
, String.toCharArray()
. But if there are any other hard code way to find the string length.
Java is an object-oriented language, where instances are encapsulated, and you access instance properties by calling methods (or directly accessing fields, if they are exposed / not private).
In Java, String
is a built-in class with instances and methods, other than in C, where a string is something like an array of characters without any encapsulation.
So, whatever you do with a String
, you'll end up calling built-in methods of that class, e.g.:
toCharArray()
is a built-in method.charAt()
is a built-in method.So, use the straightforward String.length()
method.