String Class in C++

 //Use of String class in CPP

#include<iostream>

#include<string>

using namespace std;

int main()

{

    string str1="compuhelp";//using = operator

    cout<<endl<<"String is "<<str1;

    cout<<endl<<"size of string is "<<str1.size();

    cout<<endl<<"Element access "<<str1[0];//displays first char

    cout<<endl<<"Element at "<<str1.at(1);//displays second char

  cout<<endl<<endl<<"Display String character by character"<<endl;

  for(int i=0;i<str1.size();i++)

    cout<<str1[i]<<" ";

  cout<<endl<<"second method to display string char by char"<<endl;

  for(int i=0;i<str1.length();i++)

    cout<<str1.at(i)<<" ";


    cout<<endl<<"use of substr function of string ";

    cout<<endl<<str1.substr(4);//displays substr starting from 4th index

    cout<<endl<<str1.substr(4,3);//displays substr from 4th index to 3 chars next

    cout<<endl<<str1.find('u');//returns 4 index of char

    cout<<endl<<str1.find('x');//returns garbage value means not found

    cout<<endl<<str1.insert(5," is ");//returns compu is help

    //cout<<endl<<str1;


   /* cout<<endl<<"Enter String:";

    cin>>str1;

    cout<<endl<<"your string is "<<str1;

    cout<<endl<<"again size of string is "<<str1.length();

    str1.append("compu");//will append string compu to str1

    cout<<endl<<"now string is "<<str1;

*/



}//end of main function


Comments