In this tutorial you will learn about the C++ Program to Find length of String and its application with practical example.
C++ Program to Find Length of String
In this tutorial, we will learn to create a C++ program that will Find the length of String in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- Using Strings in C++ Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking input strings from the user. 3. Concatinating the string from the taken variable. 4. Printing the result string. 5. End |
Program to Find the length of String
In this program, we will take the input as a string from the user and then we will find the length of the input string. Using the predefined string function from the c++ libraries.
With the help of this below program, we can find the length of the String.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> using namespace std; int main () { //declaring the variables for the program string str1, str2, result; // declaring the string variables int i; //declaring the integer variables //taking input string1 from the user cout <<" Enter the first string: "; cin >> str1; // take string1 //taking input string2 from the user cout << " Enter the second string: "; cin >> str2; // take second string // use for loop to enter the characters of the str1 into result string for ( i = 0; i < str1.size(); i++) { result = result + str1[i]; // add character of the str1 into result } // use for loop to enter the characters of the str2 into result string for ( i = 0; i < str2.size(); i++) { result = result + str2[i]; // add character of the str2 into result } cout << " The Concatenation of the string " << str1 << " and " << str2 << " is " <<result; //printing the size of the string cout<< endl; cout <<"String Length = " << result.size(); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- str1 = it will hold the string value.
- str2 = it will hold the string value.
- result = it will hold the string value.
- i = it will hold the integer value.
Taking Input string from the user for copying the string.
Printing the output size of the string.