This is the C++ tutorial where we will write a C++ program to find the length of a string without using a library function or any built-in function such as strlen() function. If you want to learn more about string in C++, click the link below.
Explanation: The program takes the string value from the user as an input and then using for loop or while loop, we can find the length of that string as shown in the program below.
There is no use of library function to find the length, it is totally logic-based using loops in C++.
C++ Program to Find the Length of a String without using strlen
Source code: Find Length of String without strlen() Function in C++.
using namespace std;
int length = 0, i = 0;
cout << "Enter the String: ";
cin >> str;
cout << "\nLength of a string: " << length;
Enter the String: simple2code
Length of a string: 11
You can also use for loop instead of while loop in the following manner.
for(i = 0; str[i] != '\0'; i++)
Replace the above code in place of the while loop then you will still get the same result. However, if you want to enter the string with spaces, use
gets(str) instead of
Also, you may go through the following program:
String Pattern Programs in C
Java Program to Find pair of Integers in Array whose sum is given Number
Program to Print Diamond Alphabet Patterns in C
Half Diamond Pattern in C using Alphabets
Half Pyramid of Alphabets in C