Tutorialspoint
Problem
Solution
Submissions

Length of a String

Certification: Basic Level Accuracy: 70% Submissions: 10 Points: 5

Write a C++ program that finds the length of a given string without using the `strlen()` function.

Example 1
  • Input: string = "Hello"
  • Output: 5
  • Explanation:
    • Step 1: Initialize a counter variable to 0.
    • Step 2: Iterate through the string until reaching the null terminator.
    • Step 3: Increment the counter for each character encountered.
    • Step 4: Return the final counter value.
Example 2
  • Input: string = "C++ Programming"
  • Output: 15
  • Explanation:
    • Step 1: Initialize a counter variable to 0.
    • Step 2: Iterate through the string until reaching the null terminator.
    • Step 3: Increment the counter for each character encountered.
    • Step 4: Return the final counter value.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • The string contains printable ASCII characters.
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(1)
StringsControl StructuresTech MahindraDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate through the string using a loop until the null character (`'\0'`) is encountered.
  • Count the number of characters iterated.

Steps to solve by this approach:

 Step 1: Define a function stringLength that takes a constant character pointer as parameter.
 Step 2: Initialize a length counter to zero.
 Step 3: Loop through the string until the null terminator is encountered.
 Step 4: Increment the length counter for each character.
 Step 5: Return the final length value.
 Step 6: In main, call stringLength with a string and print the result.

Submitted Code :