Program to Find Length of String
- Write a program to Find Length of String in C
- Write a program to Find Length of String in C++
- Write a program to Find Length of String in Python
- Write a program to Find Length of String in PHP
- Write a program to Find Length of String in Java
- Write a program to Find Length of String in Java Script
- Write a program to Find Length of String in C#
Explanation:
Counting the characters in a string till the end is reached is the logic used to determine its length. The general strategy is as follows:
Logic Steps:
- Initialize a Counter:
- Start a counter variable at 0.
- Traverse the String:
- Iterate through each character in the string.
- Count Characters:
- For every character encountered (excluding the null terminator NULL in C/C++), increment the counter.
- Output the Count:
- Once the end of the string is reached, the counter holds the total number of characters.
Program to Find Length of String
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
// Scan the string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Use fgets to read the string
// Find and print the length of the string
int length = strlen(str) - 1; // Subtract 1 to exclude the newline character
printf("Length of the string: %d\n", length);
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str;
// Scan the string
std::cout << "Enter a string: ";
std::getline(std::cin, str); // Read the string with spaces
// Find and print the length of the string
int length = str.length();
std::cout << "Length of the string: " << length << std::endl;
return 0;
}
str = input("Enter a string: ")
# Find and print the length of the string
length = len(str)
print("Length of the string:", length)
<?php // Scan the string echo "Enter a string: "; $str = trim(fgets(STDIN)); // fgets reads input and trim removes newline // Find and print the length of the string $length = strlen($str); echo "Length of the string: " . $length . "\n"; ?>
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Initialize scanner object for user input
Scanner scanner = new Scanner(System.in);
// Scan the string
System.out.print("Enter a string: ");
String str = scanner.nextLine(); // nextLine reads the entire line
// Find and print the length of the string
int length = str.length();
System.out.println("Length of the string: " + length);
}
}
let str = prompt("Enter a string: "); // Use prompt for input in browsers
// Find and print the length of the string
let length = str.length;
console.log("Length of the string: " + length);
using System;
class Program {
static void Main() {
// Scan the string
Console.Write("Enter a string: ");
string str = Console.ReadLine(); // Reads the entire line
// Find and print the length of the string
int length = str.Length;
Console.WriteLine("Length of the string: " + length);
}
}