Exercise:
Write a C++ program to determine the size of a string.
Program 1: String Object
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
string str = "Programming in C++";
cout << "Sentence: "<< str << endl;
cout <<"\nSize of the String: " << str.size(); // also str.length()
return 0;
}
Click Here to View the Output:
Sentence: Programming in C++ Size of the String: 18
Click Here to View the Explanation:
- A string
Programming in C++
was initialized in the code. size ()
function is used to calculate the string size in the code.length ()
function can also be used for this purpose.- The size is displayed on the screen.
Program 2: C Style String
Click Here to View the Solution:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "Programming in c++";
cout << "Sentence: "<< str << endl;
cout << "Size of the String: " << strlen(str);
return 0;
}
Click Here to View the Output:
Sentence: Programming in C++ Size of the String: 18
Click Here to View the Explanation:
- This code is similar to program 1. It just accepts a
Character Style
String from the user and not thestring object
like program 1.