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.
Author: Amod Mahajan
My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning