An interview candidate was asked to write java code to find the length of given string WITHOUT USING LENGTH METHOD in Capgemini.
In this post, I will find length of string without using Length method but using some other method. :-p
There is another method in String class called lastIndexOf().
As per Javadoc,
public int lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring. The last occurrence of the empty string “” is considered to occur at the index value
Highlighted in bold in above string is my solution actually. We will find last Index of an empty string (“”) which will give me length of actual string. Noter here, this method returns an index which starts from zero but here last occurrence of the empty string “” is considered to occur at the index value
If you like my posts, please like, comment, share and subscribe.