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++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { char str[100]; int length = 0, i = 0; cout << "Enter the String: "; cin >> str; while (str[i]) { length++; i++; } cout << "\nLength of a string: " << length; return 0; } |
Output:
Enter the String: simple2code
Length of a string: 11
You can also use for loop instead of while loop in the following manner.
1 2 3 4 | for(i = 0; str[i] != '\0'; i++) { length++; } |
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 cin >>str
.
Also, you may go through the following program: