June 22, 2022

Find Length of String Without Using length() Method in Java

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

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

No comments:

Post a Comment