Saturday 21 March 2009

Basic String manipulation example

The following is a basic string manipulation example


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program intends to show basic string operations
#include<iostream>
#include<string>

using namespace
std;

int
main(void)
{

//Lets ask for a name and make a banner to welcome the person
//Adapted from Accelerated C++ by Andrew Koenig and Barbara Moo
string name;
cout << "\nHello, what is your name? ";
cin >> name;
cout << "\n\n\n\n";
string banner = "Welcome " + name; //String addition
int bannerSize = banner.size(); //We use this size for everything
string stars((bannerSize + 4), '*');
string filler(bannerSize, ' ');
cout << stars << endl;
cout << "* " << filler << " *" << endl;
cout << "* " << banner << " *" << endl;
cout << "* " << filler << " *" << endl;
cout << stars << endl;

//Now lets check some basic string pointer operations
cout<<"\n\n\n\n";
string strs;
{

char
*text="Some program";
cout<<"text = "<<text<<endl;

//copying char* to string
strs = text;
//text[0]='A'; //-- Not possible. Run time crash as text is const pointer
cout<<"str locally = "<<strs<<endl;
}

cout<<"str globally = "<<strs<<endl;

return
0;
}



The output is as follows:

1 comment:

  1. It's Nice. I like It.
    Its Very helpfull for fresher or new students in c & c++ becouse string manipulation as an important part of C C++ programming

    ReplyDelete