String Operations in c++ part3

 This post shows the remaining string operations as follows.

  • Substring extraction
  • Searching an element
  • Other String operations using built-in functions

Substring extraction:

              It extracts the part of string. This program reads a character from the user. Using the ‘substr()’ function,it extracts a substring and display it in the output screen.

C++ Program:

#include <iostream>

#include <string>

using namespace std;

int main() {

    string st1 = "C++ Programming";

    string sub_str1 = st1.substr(4, 14);  

    cout << "Substring 1: " << sub_str1<< endl;

    string sub_str2 = st1.substr(0, 3); 

    cout << "Substring 2: " << sub_str2 << endl;

    return 0;

}

Output:

Substring 1: Programming

Substring 2: C++

Next one is searching an element.

Searching an element:

              Searching an element is finding an element. This program reads a string from the user.

Built-in function:

  • ·       ‘find()’ – it extracts a particular string.
  • ·       Based on the string, it searches in the main string and finds the position.
  • ·       Finally, it prints the location.

C++ Program:

#include <iostream>

#include <string>

using namespace std;

int main() {

    string st = "C++ Programming";

    size_t str_pos = st.find("Programming"); 

    if (str_pos < st.size()) {

        cout << "\"Programming\" found at index: " << str_pos << endl;

    }

    return 0;

}

Output:

"Programming" found at index: 4

Other String operations using built-in functions:

              The remaining built-in functions are given below.

‘compare()’- it compares two strings.

‘clear()’ – removes all characters.

‘erase()’-it erases a part of string.

‘find()’ – it searches a string.

‘length()’ – it gives you the length of the string.

‘push_back()’ – push the string

‘pop_back()’ – it pops the characters from the string.

‘strncpy()’- ‘n’ bytes are copied to another string.

‘strcmp()’ – it compares the string.

‘strcat()’- it concatenates the string.

‘substr()’- it gives you a part of string. You can make use of it for other string operations.

‘swap()’ – it exchanges two strings.

‘size()’ – it gives you the size of the string.

‘resize()’ – you can resize the string.

‘replace()’ – it replaces a string.

These are the various built-in functions in c++. Hope, you understood the concepts. 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.