In interviews some time people are ask to write a Java program to find string length without using length() method of the Java String class.
There are a couple of ways to find the length of the String with out using length method in Java. You can convert the passed string to char array and iterate through it to get the count of characters which will be the length of the String.
If you are allowed to use any other Java API method except length() method then you can also get the length of the string using lastIndexOf() method of the String class.
Java code to find length of the String without using length method
public class StringLength { public static void main(String[] args) { int strLen = strLengthWithArray("Test Line"); System.out.println("Length of the String- " + strLen); System.out.println("----------------------"); strLen = strLengthWithIndex("Test Line with index"); System.out.println("Length of the String- " + strLen); } private static int strLengthWithArray(String str){ char[] charArr = str.toCharArray(); int count = 0; for(char c : charArr){ count++; } return count; } private static int strLengthWithIndex(String str){ int count = str.lastIndexOf(""); return count; } }
Output
Length of the String- 9 ---------------------- Length of the String- 20
Related Posts
- Java Program to Count The Frequency of Each Character in a String
- Java Program to Reverse Each Word in a String
- Java Program to Find First Non-Repeated Character in The Given String
- Java Program to Swap Two Numbers Without Using Third Variable
- Java Program to Check if Armstrong Number
- Java Program to Find The Maximum Element in Each Row of a Matrix
- How to Copy a Directory in Java
- Print Numbers Sequentially Using Three Threads in Java
Check out the compilation of Top 40 Java blogs on the web – Top 40 Java Blogs, Websites & Newsletters For Programmers in 2019
That’s all for the topic Find Length of String Without Using length() Method in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like