Tutorialspoint
Problem
Solution
Submissions

Length of a String

Certification: Basic Level Accuracy: 53.33% Submissions: 45 Points: 5

Write a C++ program that finds the length of a string using pointers.

Example 1
  • Input: string = "hello"
  • Output: 5
  • Explanation:
    • Step 1: Initialize a pointer to the start of the string.
    • Step 2: Initialize a counter to 0.
    • Step 3: Increment the counter and move the pointer to the next character.
    • Step 4: Repeat step 3 until the null character is encountered.
    • Step 5: Return the counter value as the length of the string.
Example 2
  • Input: string = "world"
  • Output: 5
  • Explanation:
    • Step 1: Initialize a pointer to the start of the string.
    • Step 2: Initialize a counter to 0.
    • Step 3: Increment the counter and move the pointer to the next character.
    • Step 4: Repeat step 3 until the null character is encountered.
    • Step 5: Return the counter value as the length of the string.
Constraints
  • 1 ≤ string length ≤ 10^6
  • Use pointers to find the length
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(1)
StringsPointers and ReferencesTech MahindraShopify
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

  • Use a pointer to traverse the string until the null character ('\0') is encountered.
  • Count the number of characters traversed.

Steps to solve by this approach:

 Step 1: Define a function string_length that takes a constant character pointer as parameter.

 Step 2: Initialize a counter variable to zero.
 Step 3: While the current character is not the null terminator, increment the counter.
 Step 4: After each increment, move the pointer to the next character.
 Step 5: Return the final counter value, which represents the string length.
 Step 6: In main, declare a constant character pointer with a string value.
 Step 7: Call string_length with this pointer and print the result.

Submitted Code :