manipulating string in c++

Introduction-:  A string is a sequence of character. we know that the c++ does not  support a build string type. We have use earlier null terminated character array to store and manipulate string. These string are called C string or C style string.

ANSI standard c++ now provide a special new class called string. this class improve on the conventional C string in several ways.In many condition it is not considered as a part of the Standard template Library string is treated as another container class by c++ and therefore all the algorithm that are applicable for container can be used with the string object.

 

String class is very large and includes many constructors, member function and operation.

Creating string object-: We can create String object in a number of ways as like

string s1;

string s2("xyz");

s1 = s2;

s3 ="abc" + s2

cin >> s1;

getline (cin, s1);

 

 

Manipulating string Object -: We can modify contents of string object in several way. using the member function such as insert(), erase (), and append(), replace(),.

# include<iostream>
# include<string>

using namespace std;

int main()

  {


     string s1("12345");
     string s2("abcde");

     cout << " original string are: \n ";
     cout << "s1:" << s1 << "\n";
     cout << "s2 :" << s2 << "\n";
  

// inserting a string into another
     cout << "place s2 inside  s1 \n"
     s1.insert(4,s2)

     cout << "modified s1: " <<s1 <<"\n";

//removing character in string 
     cout << "remove 5 character from s1 \n";

      s1.erase (4,5);

     cout << "now s1: " <<s1 <<"\n";
//replacing character in a string

    cout << " replacing middle 3 character in s2 with s1 \n";
    s2.replace(1,3,s1);
    
    cout << "Now s2: " << s2 <<"\n";

return 0;
}

Output of this programe

Original string are 
s1: 12345
s2: abcde

place s2 inside s1
modified s1: 1234abcde5

remove 5 character from s1
now s1: 12345

replace middle 3 character in s2 with s1
Now s2: a12345e

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *