You are on page 1of 14

C++ Strings

Prepared by: Rowena S. David


C++ Strings
A string is a collection of characters.
C++ provides following two types of
string representations:
• The C-style character string.
• The string class type introduced with
Standard C++.
• The C-Style Character String
The C-style character string originated within the
C language and continues to be supported within
C++.

This string is actually a one-dimensional array of


characters which is terminated by a null character
'\0'.
• The C-Style Character String
For example:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";
C++ program to display a string entered by user.

#include <iostream>
using namespace std;
int main()
{ char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str <<endl;
return 0;
}
C++ program to read and display an entire line entered by user.
#include <iostream>
using namespace std;

int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);

cout << "You entered: " << str << endl;


return 0;
}
C++ string using string data type

#include <iostream>
getline() function takes the input stream
using namespace std; as the first parameter which is cin and str
as the location of the line to be stored.
int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);

cout << "You entered: " << str << endl;


return 0;
}
The String Class in C++
#include <iostream>
#include <string>
using namespace std;
int main ()
{ string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
str3 = str1;
cout << str3 << endl;

str3 = str1 + str2;


cout << str3 << endl;
len = str3.size();
cout << len << endl;
return 0;
}
Write a C++ that will generate this output:
Lab Exercise:

Write a C++ program than will allow the user to guess a


password. User has three attempts to input the correct
password.
After three failed attempts, the program should exit.
Lab Exercise:

A palindrome is a word, number, phrase, or other sequence of


characters which reads the same backward as forward.

Create a C++ program that will determine if a given string is a


palindrome.

Enter a string: Hello there.


String is not a palindrome.

Enter a string: Mr. Owl ate my metal worm


String is a palindrome