The Wayback Machine - https://web.archive.org/web/20241002060112/https://www.geeksforgeeks.org/c-string-class-and-its-applications/
Open In App

C++ string class and its applications

Last Updated : 14 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

In C++ we can store string by one of the two ways –

  1. C style strings
  2. string class (discussed in this post)

In this post, the second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store character but all memory management, allocation, and null termination is handled by string class itself that is why it is easy to use. The length of the C++ string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string class is a container class, we can iterate over all its characters using an iterator similar to other containers like vector, set and maps, but generally, we use a simple for loop for iterating over the characters and index them using the [] operator. C++ string class has a lot of functions to handle string easily. Most useful of them are demonstrated in below code.

CPP




// C++ program to demonstrate various function string class
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // various constructor of string class
 
    // initialization by raw string
    string str1("first string");
 
    // initialization by another string
    string str2(str1);
 
    // initialization by character with number of occurrence
    string str3(5, '#');
 
    // initialization by part of another string
    string str4(str1, 6, 6); //    from 6th index (second parameter)
                             // 6 characters (third parameter)
 
    // initialization by part of another string : iterator version
    string str5(str2.begin(), str2.begin() + 5);
 
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    cout << str4 << endl;
    cout << str5 << endl;
 
    //  assignment operator
    string str6 = str4;
 
    // clear function deletes all character from string
    str4.clear();
 
    //  both size() and length() return length of string and
    //  they work as synonyms
    int len = str6.length(); // Same as "len = str6.size();"
 
    cout << "Length of string is : " << len << endl;
 
    // a particular character can be accessed using at /
    // [] operator
    char ch = str6.at(2); //  Same as "ch = str6[2];"
 
 
    cout << "third character of string is : " << ch << endl;
 
    //  front return first character and back returns last character
    //  of string
 
    char ch_f = str6.front();  // Same as "ch_f = str6[0];"
    char ch_b = str6.back();   // Same as below
                               // "ch_b = str6[str6.length() - 1];"
 
    cout << "First char is : " << ch_f << ", Last char is : "
         << ch_b << endl;
 
    // c_str returns null terminated char array version of string
    const char* charstr = str6.c_str();
    printf("%s\n", charstr);
 
    // append add the argument string at the end
    str6.append(" extension");
    //  same as str6 += " extension"
 
    // another version of append, which appends part of other
    // string
    str4.append(str6, 0, 6);  // at 0th position 6 character
 
    cout << str6 << endl;
    cout << str4 << endl;
 
    //  find returns index where pattern is found.
    //  If pattern is not there it returns predefined
    //  constant npos whose value is -1
 
    if (str6.find(str4) != string::npos)
        cout << "str4 found in str6 at " << str6.find(str4)
             << " pos" << endl;
    else
        cout << "str4 not found in str6" << endl;
 
    //  substr(a, b) function returns a substring of b length
    //  starting from index a
    cout << str6.substr(7, 3) << endl;
 
    //  if second argument is not passed, string till end is
    // taken as substring
    cout << str6.substr(7) << endl;
 
    //  erase(a, b) deletes b characters at index a
    str6.erase(7, 4);
    cout << str6 << endl;
 
    //  iterator version of erase
    str6.erase(str6.begin() + 5, str6.end() - 3);
    cout << str6 << endl;
 
    str6 = "This is a examples";
 
    //  replace(a, b, str)  replaces b characters from a index by str
    str6.replace(2, 7, "ese are test");
 
    cout << str6 << endl;
 
    return 0;
}


Output :

first string
first string
#####
string
first
Length of string is : 6
third character of string is : r
First char is : s, Last char is : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
These are examples

As seen in the above code, we can get the length of the string by size() as well as length() but length() is preferred for strings. We can concat a string to another string by += or by append(), but += is slightly slower than append() because each time + is called a new string (creation of new buffer) is made which is returned that is a bit overhead in case of many append operation. 
Applications : On basis of above string function some application are written below : 

CPP




// C++ program to demonstrate uses of some string function
#include <bits/stdc++.h>
using namespace std;
 
// this function returns floating point part of a number-string
string returnFloatingPart(string str)
{
    int pos = str.find(".");
    if (pos == string::npos)
        return "";
    else
        return str.substr(pos + 1);
}
 
// This function checks whether a string contains all digit or not
bool containsOnlyDigit(string str)
{
    int l = str.length();
    for (int i = 0; i < l; i++)
    {
        if (str.at(i) < '0' || str.at(i) > '9')
            return false;
    }
    //  if we reach here all character are digits
    return true;
}
 
// this function replaces all single space by %20
// Used in URLS
string replaceBlankWith20(string str)
{
    string replaceby = "%20";
    int n = 0;
 
    // loop till all space are replaced
    while ((n = str.find(" ", n)) != string::npos )
    {
        str.replace(n, 1, replaceby);
        n += replaceby.length();
    }
    return str;
}
 
// driver function to check above methods
int main()
{
    string fnum = "23.342";
    cout << "Floating part is : " << returnFloatingPart(fnum)
         << endl;
 
    string num = "3452";
    if (containsOnlyDigit(num))
        cout << "string contains only digit" << endl;
 
    string urlex = "google com in";
    cout << replaceBlankWith20(urlex) << endl;
 
    return 0;     
}


Output :

Floating part is : 342
string contains only digit
google%20com%20in

Time Complexity : O(N),   here N is length of string .

Space Complexity : O(1) , since we not used any extra space.

Related Articles:



Previous Article
Next Article

Similar Reads

C++ String Class and its Applications
C++ string class and its applications have more functions as discussed in this article String vs Character Array In C++, in addition to a character array, there exists a similar kind of way to implement string, that is using a string class which is a part of C++ standard library.We need to add a header file to implement string using string class. T
4 min read
Different Types of Queues and its Applications
Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the different types of queues are discussed. Types of Queu
8 min read
strchr() function in C++ and its applications
In C++, strchr() is a predefined function used for finding the occurrence of a character in a string. It is present in cstring header file. Syntax: // Returns pointer to the first occurrence// of c in str[]char *strchr(const char *str, int c) Note that c is passed as its int promotion, but it is internally treated as char.Application Given a string
4 min read
MakeFile in C++ and its applications
In C++, building a simple program is easy with the help of CLI of the compiler. But it becomes progressively difficult to maintain and build the project when its size increases. We may need to write multiple lines of commands just to simply compile it. This can be simplified by using Makefile for the project and build it using this makefile. In thi
5 min read
stringstream in C++ and its Applications
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input. Basic methods are: clear()- To clear the stream.str()- To get and set string object whose content is
3 min read
Count of Array elements greater than all elements on its left and next K elements on its right
Given an array arr[], the task is to print the number of elements which are greater than all the elements on its left as well as greater than the next K elements on its right. Examples: Input: arr[] = { 4, 2, 3, 6, 4, 3, 2}, K = 2 Output: 2 Explanation: arr[0](= 4): arr[0] is the 1st element in the array and greater than its next K(= 2) elements {2
14 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
15+ min read
Smallest N digit number with none of its digits as its divisor
Given an integer N. The task is to find the smallest N digit number S, such that S is not divisible by any of its digits. Print -1 if no such number is possible.Examples: Input: N = 2 Output: 23 Explanation: 23 is the smallest two-digit number that is not divisible by any of its digits.Input: N = 1 Output: -1 Explanation: Every single digit number
10 min read
Node having maximum number of nodes less than its value in its subtree
Given a Binary Tree, the task is to find the node from the given tree which has the maximum number of nodes in its subtree with values less than the value of that node. In the case of multiple possible nodes with the same number of maximum nodes, then return any such node. Examples: Input: 4 / \ 6 10 / \ / \2 3 7 14 / 5 Output: 6Explanation:Node wi
10 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Lexicographically largest array possible from first N natural numbers such that every repetition is present at distance equal to its value from its previous occurrence
Given a positive integer N, the task is to construct the lexicographically largest array of size (2 * N - 1) comprising of first N natural numbers such that each element occurs twice except 1 and the repetition of X is exactly X distance apart in the constructed array. Examples: Input: N = 4Output: 4 2 3 2 4 3 1Explanation:For the generated array {
10 min read
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X
Given two positive integers X and K, the task is to find the Kth smallest positive integer (Y) such that the sum of X and Y is equal to Bitwise OR of X and Y, i.e. (X + Y = X | Y) Examples: Input: X = 5, K = 1Output: 2Explanation:Consider the smallest number as 2. The sum of 2 and 5 is 2 + 5 = 7 and the Bitwise OR of 2 and 5 is 7. Input: X = 5, K =
6 min read
Find GCD of all Array numbers for which its value is equal to its frequency
Given an array arr[] of integers N, the task is to find the GCD of all numbers for which it's value is equal to its frequency in the array. Examples; Input: arr={2, 3, 4, 2, 3, 3} N=6 Output: 1Explanation: Here 2 is occurring 2 times and 3 is occurring 3 times. Hence GCD of 2, 3, is 1. So our output is 1. Input: arr={2, 3, 4, 4, 3, 5, 4, 4, 2, 8} N
6 min read
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right
Given an array, arr[] size N, the task is to find the smallest index of the array such that the sum of all the array elements on the left side of the index is equal to the reverse of the digits of the sum of all the array elements on the right side of that index. If no such index is found then print -1. Examples: Input: arr[] = { 5, 7, 3, 6, 4, 9,
15+ min read
Lexicographically smallest and largest anagrams of a string containing another string as its substring
Given two strings S1 of size N and S2 of size M, the task is to find the lexicographically smallest and the largest anagrams of S1 such that it contains the string S2 as a substring. Examples: Input: S1 = "hheftaabzzdr", S2 = "earth" Output: abdearthfhzz, zzhfearthdba Explanation: The smallest anagram of the given string S1 with S2 as a substring i
13 min read
Length of String formed by repeating each character in range [L, R] of given string its lexicographic value times
Given a string S of length N, and a range [L, R] (1 <= L, R <= N). The task is to find the length of string formed by repeating each character in the range [L, R], to its lexicographical value times. Examples: Input: s = "cbbde", l = 2, r = 5Output: 13Explanation: Resultant String is formed after repeating each character in range [2, 5] as sh
9 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 min read
Rearrange a string S1 such that another given string S2 is not its subsequence
Given two strings S1 and S2 of size N and M respectively, the task is to rearrange characters in string S1 such that S2 is not a subsequence of it. If it is not possible to make such rearrangements, then print "-1". Otherwise, print the rearranged string S1. Examples: Input: S1 = "abcd", S2 = "ab"Output: "dcba"Explanation:Rearrange the string S1 as
10 min read
Check if a string contains an anagram of another string as its substring
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the problem: Initialize two Hashmaps s1hash and s2has
7 min read
Find the count of palindromic sub-string of a string in its sorted form
Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input: str = "abbabdbd" Output: 16 Naive approach: One
5 min read
Applications, Advantages and Disadvantages of String
The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequences in a variety of ways. The string data struct
6 min read
Class 10 RD Sharma Solutions - Chapter 12 Some Applications of Trigonometry - Exercise 12.1 | Set 3
Question 53. From the top of a building AB, 60 m high, the angles of depression of the top and bottom of a vertical lamp post CD are observed to be 30° and 60° respectively. Find (i) the horizontal distance between AB and CD. (ii) the height of the lamp post (iii) the difference between the heights of the building and the lamp post. Solution: Let u
15+ min read
Class 10 RD Sharma Solutions - Chapter 12 Some Applications of Trigonometry - Exercise 12.1 | Set 2
Question 27. A T.V. tower stands vertically on a bank of a river of a river. From a point on the other bank directly opposite the tower, the angle of elevation of the top of the tower is 60°. From a point 20 m away this point on the same bank, the angle of elevation of the top of the tower is 30°. Find the height of the tower and the width of the r
15+ min read
Class 10 RD Sharma Solutions - Chapter 12 Some Applications of Trigonometry - Exercise 12.1 | Set 1
In this article, we will delve into the solutions for Exercise 12.1 Set 1 from Chapter 12 of RD Sharma's Class 10 Mathematics textbook which focuses on the "Some Applications of Trigonometry". This chapter introduces practical applications of trigonometric ratios and concepts providing the students with the tools to solve real-world problems involv
15+ min read
Applications of String Matching Algorithms
String matching algorithms have greatly influenced computer science and play an essential role in various real-world problems. It helps in performing time-efficient tasks in multiple domains. These algorithms are useful in the case of searching a string within another string. String matching is also used in the Database schema, Network systems.Let
5 min read
Longest Palindrome in a String formed by concatenating its prefix and suffix
Given a string str consisting of lowercase English letters, the task is to find the longest palindromic string T which satisfies the following condition: T = p + m + s where p and s are the prefix and the suffix of the given string str respectively and the string m is either the prefix or suffix of the string str after removing both p and s from it
13 min read
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Given a string str of N characters, the task is to find the lexicographically smallest string that can be formed by concatenating any prefix and its mirrored form. Examples: Input: str = "geeksforgeeks"Output: geeeegExplanation: The lexicographically smallest string can be formed with the prefix "gee" as "gee" + "eeg". Input: str = "abcd"Output: aa
5 min read
Applications, Advantages and Disadvantages of Branch and Bound Algorithm
Branch and bound algorithm is a method used in computer science to find the best solution to optimization problems. It systematically explores all potential solutions by breaking the problem down into smaller parts and then uses limits or rules to prevent certain parts from being considered. Applications of Branch and Bound:Combinatorial Optimizati
2 min read
INT_MAX and INT_MIN in C/C++ and Applications
Most of the time, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C/C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without ac
7 min read