String Operations in C++ part2

               Part1 includes the basic functionality of strings. This post explains the string operations for the following functionalities.

  • Length of a String
  • Modification of a string

Length of a String:

              This function finds the number of characters in the String. It uses two method. One is ‘size()’ and second one is ‘length()’.

Program:

#include <iostream>

#include <string>

using namespace std;

int main() {

    string st1 = "C++ Programming";

    //first method (size())

    cout << "Length of the string using size(): " << st1.size() << endl;

    // Second method (length())

    cout << "Length of the string using length(): " << st1.length() << endl;

    return 0;

}

Output:

Length of the string using size(): 15

Length of the string using length(): 15

Next one is modification of a string.

Modification of a string:

              This includes the addition of a character or a substring, remove a character or set of characters. It uses ‘push_back()’, ‘pop_back()’,’insert()’ and ‘erase()’ built-in functions.

Program:

#include <iostream>

#include <string>

using namespace std;

int main() {

 string st1 = "C++ Programming";

 // let us Add a character at the end of the string

 st1.push_back('!');

 cout << "After inserting a character at the end( push_back) :" << st1 << endl;

    // Delete the last character

    st1.pop_back();

    cout << "After deletion of last character(pop_back): " << st1 << endl;

    // adding a substring to string

    st1.insert(3,",Java ");

    cout << "After adding the substring: " << st1 << endl;

    // Delete a sub string

    st1.erase(9, 19);

    cout << "After the deletion: " << st1 << endl;

    return 0;

}

Output:

After inserting a character at the end( push_back) :C++ Programming!

After deletion of last character(pop_back): C++ Programming

After adding the substring: C++,Java  Programming

After the deletion: C++,Java

Hope, these coding parts are useful to you. Part3 post includes searching and substring extraction functions. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.