JAVA program to find length of a string without using string method

JAVA program to find length of a string without using string method

This JAVA program is to find length of string without using string method.

For example, if string=”Coding” then the length of string=6.

Logic

In this program we use toCharArray method in java to convert the string into character array. We then count the number of characters using for each loop of java where ‘:‘ means ‘in’ that is for char c in char array ch increment i. Hence we get the length of the string.

There are many other ways like append a character at the end of a string and break as soon as you reach it or use StringIndexOutOfBoundsException.

Program

import java.util.*;

class stringLength
{
	public static void main(String args[])
	{
		int i=0;
		String str;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the string");
	 	str=sc.nextLine();
		char ch[]=str.toCharArray();
		
		for(char c : ch)
		{
			i++;	
    		}
        	System.out.println("Length of the string = "+i);
	}
}

Output

 

 

 

Share Me!