Q. Program to find length of given string.



String :- The string is defined as an array of characters. The difference between a character array and a string is the string ending with a special character '\0'.

For Eg :- If the string is "hello", the output is 5.

Algorithm to find length of string

START
    Step 1:Length = 0
    Step 2: Repeat step 3 while S1 [Length] ≠ NULL
    Step 3: Length = Length + 1
    Step 4: Return Length
STOP


Program to find length of string

  • C
  • C++
  • Java
  • Python
  • C#
  • PHP
  •  
    #include <stdio.h>
    #include <string.h>
     
    int main()
    {
      char a[100]="Letsfindcourse";
      int length;
    
      for (int i = 0; a[i] != '\0'; i++)
    	  lenght += 1;
    
      printf("Length of the string = %d\n", length);
    
      return 0;
    }
    
    #include<iostream>
    using namespace std;
    
    int main()
    {
        string str = "Letsfindcourse";
    
        // you can also use str.length()
        cout << "Length of the string = " << str.size();
    
        return 0;
    }
    
    public class Main {
        public static void main(String[] args) {
            //declare the String as an object S1 S2
            String S1 = "Letsfindcourse";
            //length() method of String returns the length of a String S1.
            int length = S1.length();
            System.out.println("Length of the string = " + length);
        }
    }
    
    str1 = "Letsfindcourse"
    print("Length of the string =",len(str1)) 
    
    using System;  
    public class LFC
    {  
        public static void Main() 
    {
        string str1="Letsfindcourse"; /* Declares a string of size 100 */
        int l= 0;
    
             foreach(char chr in str1)
            {
                l += 1;
    
            }
    
       Console.Write("Length of the string = {0}\n\n", l);
      }
    }
    
    $str1=strlen("Letsfindcourse");
    echo "Length of the string = $str1";
    
    #include <stdio.h>
    #include <string.h>
     
    int main()
    {
      char a[100]="Letsfindcourse";
      int length;
    
      length = strlen(a);
    
      printf("Length of the string = %d\n", length);
    
      return 0;
    }
    

    Output

    Length of the string = 14
    

    Recommended Programs

       Program to check if string is anagram or not
       Program to check substring of a string