Monday, June 17, 2013

C++ Strings Introduction | C++ Tutorial

A String is a sequence of characters, such as "Singh". In C++ strings are enclosed in quotation marks. To declare a variable of type string you have to include the header file for strings: #include <string> and the syntax to declare a variable that hold strings: string fruit = "apple";.

To read a string from user input:
cout << "What is your favorite Fruit?"
cin >> fruit;

When a string is read by the compiler, only one word is placed in the string variable. (Words separate by white spaces) If user input is Honeydew melon, then only Honeydew is placed into the string variable fruit. To read the entire name (more than one word) of the fruit you can use: getline(cin, fruit);, which will read all letters including white spaces until Enter key.

The length of a string is the number of characters in a string, such as "apple" length is 5. To compute the length of a string, you can use the length function, invoked with the dot operator: int fruitlength = fruit.length();. A string with no characters is an empty string, "".

A string starting position is 0, second one is 1 and so on. Here is an example:
0    1     2    3    4
A   P    P    L   E

Once you have a string, you can do various things with it, concatenate (join together) it or you can extract smaller strings from it. To extract a sub-string from a string, you can use the substr member function. The syntax is s.substr(start, length);. Here is an example:
string fruit = "Pineapple";
string subfruit = fruit.substr(4, 5);
// subfruit is "apple"
The subfruit string basically starts at the 4th position and the length of the subfruit string is 5. If the length was 4, the output would be appl.

To Concatenate two strings you can use the + operator. Here is an example:
string firstname = "Gurpreet";
string lastname = "Singh";
string fullname = firstname + " " + lastname;

To understand the concept of this tutorial, here is a simple program that asks user for full name and prints out initials.
#include <iostream>
#include <string>
using namespace std;

void main ()
{
    string firstname;
    string lastname;
    string initials;
    cout << "Enter Full Name: (First Last)" << endl;
    cin >> firstname >> lastname;
    initials = firstname.substr(0,1) + lastname.substr(0,1);

    cout << "You Initials are: " <<initials <<endl;

    system("pause");
}

No comments:

Post a Comment