1
votes

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.

1
Pretty much just what you said. String.toCharArray() then count each iteration until you get an ArrayIndexOutOfBoundsException. But...why?j.seashell
Yes, sir, it is easier and readable with these functions but if there is any other way, I just wanted to know. ThanksVhndaree
You could make it like C. Just append '\0' to the end of your string, and use the method from C.Raghav
"there are various inbuilt functions, using which we can count string length like lastIndexOf()" lastIndexOf doesn't provide length of array, but last index which holds specified value. "if there are any other hard code way to find the string length" what do you mean by hard code here? Can you include example of what you are searching and rationale explaining why / how you want to use it?Pshemo
@all Whatever you do with a String, you'll be calling built-in methods of String or of StringBuilder (in case of appending).Ralf Kleberhoff

1 Answers

2
votes

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.