|
Manipulating String Variables
A string is a sequence of characters. In order to use strings in
your programs, you need to first make sure that you are using a recognized
string library. This can be achieved by adding the following
to the top of your code (where you place your header files):
#include<string.h>
using namespace std; The
second line tells the compiler to use the standard "namespace"
for the string library. The
rest is fairly simple. Here is how a sample program using strings
would look like:
#include <iostream>
#include <string>
using namespace std;
void main()
{
string firstname="test";
cout << "Enter first name: ";
cin >> firstname;
cout << firstname << endl;
} Note
that double quotes are used for assigning values to strings.
Sometimes strings may not only contain one word. Therefore, the
function getline()
is used to get the complete line including spaces. For
example:
#include <iostream>
#include <string>
using namespace std;
void main()
{
string full_name;
cout << "Enter full name: ";
getline(cin,full_name);
cout << full_name << endl;
} Notice
the different syntax used for the getline() function.
Another thing worth mentioning is that strings can be added together, not
in the same sense as numbers, however. For example:
string number1="123";
string number2="456";
cout << number1+number2 << endl; would
give: "123456" instead of adding the two and displaying
"579".
You can get the length of a string by using the length()
function. For example:
string s="How are you today?";
int length=0;
length=s.length();
cout << length << endl;
This example
would display 18.
If you are interested in more advanced manipulations of strings (for
example, extracting sub strings, finding letters, searching and
replacing...), you may wish to take a look at C++ Coder. Click here!
{Go Back To C++ Lessons Page}
|