Java Program to find length of the string without using length function

Finding Length of string without using length() method

In this article we’re going to make a Java program to find length of String without using length() method . In this program first we will take the String input from user . After that we will convert String to character array by using toCharArray() . After that we will use for-each loop to count the length  of the String

Java Program to find length of the string without using length function

Algorithm:

  • In this program first we will take String input from user and store in the variable called s with the help of next()
  • After that we will take a for-each loop and in the paremeter of for-each loop we will convert the String to character array using toCharArray() 
  • After that for every variable we will take a variable named as count and increment this every time

Code in Java

import java.util.Scanner;

public class FindLengthOfStringWithoutUsingLength {

	public static void main(String[] args) {
		int length=0;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a String");
        String s = sc.next();
        for (char c1 : s.toCharArray()) 
			length++;
		System.out.println("Length of String is : "+length);
		
	}

}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter a String prepinsta
Length of String is : 9

4 comments on “Java Program to find length of the string without using length function”


  • Mancy

    Simple code
    import java.util.*;
    import java.util.Scanner;
    public class Main{
    public static void main(String args[])
    {
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    int i,length=0;
    for(i=0;i<str.length();i++)
    {
    length++;
    }
    System.out.println(""+length);
    }
    }


  • shiyam

    import java.util.Scanner;
    public class MyClass {
    public static void main(String args[]) {
    Scanner sc=new Scanner(System.in);
    String s=sc.nextLine();
    System.out.println(s.length());
    }
    }


  • Vaibhav

    package stringprogram;

    import java.util.Scanner;

    public class String_Length_Wihout_Using_LengthFunction {

    public static void main(String[] args)
    {
    int length=0,i=0;
    Scanner sc = new Scanner(System.in);
    System.out.println(“Enter a String”);
    String s = sc.next();
    String n=s+’\0′;
    while(n.charAt(i) != ‘\0’)
    {
    length++;
    i++;
    }
    System.out.println(“length of String is “+length);

    }
    }