String Member Functions in C++

We covered the fundamentals of String Class in C++ in our previous post. In this post, we are going to cover the several operations and functionalities that we can perform on the String type. There are several member functions that are available in string class in C++ which is veryful for solving string related coding problems. 

Here we are going to discuss all the string member functions available in C++ programming language with real example and code implementation.

String empty() function in C++.

String Function Definition
empty() This function is used to check if a string is empty or not. It returns 1 if a string is empty else returns 0 if a string is not empty.
Example C++ Code:
/*C++ program to show the working of
empty() function
*/
#include<iostream>
#include<string>
using namespace std;

int main(){
    
    string str;
    //taking input from user
    cout<<"Enter a string: ";
    getline(cin, str);
    //checking string is empty or not
    if(!str.empty()){
        cout<<"The string is: "<<str<<endl;
    }
    else{
        cout<<"The string is empty!"<<endl;
    }
    
    return 0;
}
Output:
Enter a string: 
The string is empty!
Enter a string: Algolesson
The string is: Algolesson
In the output of the above code, you can see that when I enter nothing as an input, the empty() function checks the string and executes the else part saying, "The string is empty!". You have also noticed one getline() function that takes input from the user.


String Modifier functions in C++.

String Function Definition
push_back() This function is used to add a character at the end of the string.
pop_back() This function is used to delete the last character from the string.
insert() This function is used to insert additional characters into the string.
erase() This function is used to remove the part of the string which reduce the size of the string.
Example C++ Code:
/*C++ program to show the working of erase()
insert(), push_back() and pop_back() function
*/
#include<iostream>
#include<string>
using namespace std;

int main(){
    
    string str;
    //taking input from the user
    cout<<"Enter a string: ";
    getline(cin, str);
    
    cout<<"The string is: "<<str<<endl;
    //adding a char at the end of the string
    str.push_back('s');
    cout<<"String after push_back() operation: "<<str<<endl;
    //removing a char from the end of the string
    str.pop_back();
    cout<<"String after pop_back() operation: "<<str<<endl;

    string str1 = "Rose is a ";
    str.insert(0, str1);
    cout<<"String after insert operation: "<<str<<endl;

    str.erase(10, 10);
    cout<<"String after erase operation: "<<str<<endl;
return 0; }
Output:
Enter a string: Beautiful Flower
The string is: Beautiful Flower
String after push_back() operation: Beautiful Flowers
String after pop_back() operation: Beautiful Flower
String after insert operation: Rose is a Beautiful Flower
String after erase operation: Rose is a Flower
If you are already working with string then you probably know the functionality of getline() function. In the above code, push_back('s') adds one s character at the end of our string and the pop_back() function removes that end 's' character.

String Capacity functions in C++. 

String Function Definition
capacity() This function is used to return the capacity allocated to the string which can be equal to more than the length of the string.
length() This function is used to check the length of the string.
resize() This function is used to change the size of the current string. The size of the string can be increased or decreased based on demand.
shrink_to_fit() This function is used to decrease the capacity of the string to fit its size. It makes string capacity equal to string size.
size() This function is used to find the length of the string which also indicates the number of characters present in the string.
  • The size() functional and length() function return the same value always.
Example C++ Code:
/*C++ program to show the working of resize(),
capacity() and shrink_to_fit() function
*/
#include<iostream>
#include<string>
using namespace std;

int main(){
    
    string str;
    //taking input from user
    cout<<"Enter a string: ";
    getline(cin, str);
    
    cout<<"The string is: "<<str<<endl;

    str.resize(7);
    cout<<"String after resize operation: "<<str<<endl;

    cout<<"The capacity of the string is: "<<str.capacity()<<endl;

    cout<<"The length of the string is: "<<str.length()<<endl;

    str.shrink_to_fit();
    cout<<"The capacity of the string after shrink: "<<str.capacity()<<endl;

    cout<<"The size of the string is: "<<str.size()<<endl;
return 0; }
Output:
Enter a string: Welcome to Algolesson
The string is: Welcome to Algolesson
String after resize operation: Welcome
The capacity of the string is: 30
The length of the string is: 7
The capacity of the string after shrink: 15
The size of the string is: 7
In the above, code you can see that number of characters present in the input string was 21 and after resizing the string to 7 it contains only 7 characters but the capacity of the string was still 30 and even tho the length of the string showing is 7 so after performing shrink operation to free unwanted memory the capacity reduced to 15. 

String Iterator Functions in C++.

String Function Definition
begin() This function is used to return an iterator to the beginning of the string.
end() This function is used to return an iterator to the end of the string.
rbegin() This function is used to return a reverse iterator pointing at the end of the string.
rend() This function is used to return a reverse iterator pointing at the beginning of the string.
Example C++ Code:
/*C++ program to show the working of begin(), end()
rbegin() and rend() function
*/
#include<iostream>
#include<string>
using namespace std;

int main(){
    
    string str = "Algolesson";
    
    std::string::iterator it;

    cout<<"Print String using forward iterator: ";
    for(it = str.begin(); it != str.end(); it++)
       cout<<*it;
    cout<<endl;

    std::string::reverse_iterator rit;

    cout<<"Print String using reverse iterator: ";
    for(rit = str.rbegin(); rit != str.rend(); rit++)
       cout<<*rit;   
       
    return 0;
}
Output:
Print String using forward iterator: Algolesson
Print String using reverse iterator: nosseloglA
In the above code, when we use the reverse iterator to print our string then it prints the string in reverse order because begin() points to the end of the string to it start printing in reverse order.

String Operation Functions in C++.

String Function Definition
copy() This function is used to copy a sequence of characters from the string. This function returns a char array and the function required three arguments, the name of the char array, the length of the string to be copied, and the starting position of copying. 
find() This function is used to find content in the string. It can contain two arguments,
  • First argument is the string to be searched for.
  • Second argument is the starting index at which the search is going to start.
substr() This function is used to generate a substring of the string. It contain two argument,
  • First argument is the position of first character to be copied as a substring.
  • Second argument tell us about the length of the substring.
compare() This function is used to compare two strings and return 0 if both are equal.
Example C++ Code:
/*C++ program to show the working of copy(), find()
substr() and compare() function
*/
#include<bits/stdc++.h>
#include<iostream>
#include<string>
using namespace std;

int main(){

  string str = "Coding is Fun";
  string str1 = "Programming is Fun Coding is Fun";
  string str2 = "Fun";
  
  //char array of size 20
  char copystr[20];
  int length = str1.copy(copystr, 11, 0);
  copystr[length] = '\0';
  cout<<"The copied character array is: "<<copystr<<endl;

  int found = str1.find(str2);
  cout<<"The First occurrence of str2 at: "<<found<<endl;

  found = str1.find(str2, found+1);
  cout<<"The Second occurrence of str2 at: "<<found<<endl;

  string str3 = str1.substr(19, 6);
  cout<<"The First substring is: "<<str3<<endl;

  str3 = str1.substr(19);
  cout<<"The Second substring is: "<<str3<<endl;

  if(str.compare(str3) == 0)
    cout<<"Both strings are equal."<<endl;
     
  return 0;
}
Output:
The copied character array is: Programming
The first occurrence of str2 at: 15
The Second occurrence of str2 at: 29
The First substring is: Coding
The Second substring is: Coding is Fun
Both strings are equal.
In the above code, the copy() function return the character array and with null character at the end so we need to append it sepeararately or it might cause unexpected error. The substr() function help to capture substring and usually required two argument (starting position and size of substring) but if you don't provide the size of substring then it will capture from starting position till end of the string.

I hope you found this article useful, please share your feedback in the comment section below so we can work on them to provide you the best content. 

Program to Find Kth Largest Element of an Array.

Given an array of n distinct elements and we need to find the kth largest number from the given array where the value of k is larger than the size of the given array.

Example:

Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 3
Output: 7

Input: arr[] = {4, 9, 2, 7, 3, 10}, k = 5
Output: 3

Approach 1: Using Sorting.

The simplest approach that anyone can think of is to sort the given array in ascending order and return the element present at index (n-k) and array elements are stored based on 0-based indexing. You can use the sort function given in almost all programming languages or you can use quick sort whose time complexity is O(nlogn).

C++ Code Implementation:
//C++ code to find the kth largest element of an array
#include<iostream>
#include<algorithm>
using namespace std;

//function to return kth largest element
int largestNumber(int arr[], int n, int k){
    //sort the array
    sort(arr, arr+n);

    return arr[n-k];
}

int main(){
    
    int arr[] = {4, 9, 2, 7, 3, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
    cout<<"The kth largest element is: "<<largestNumber(arr, n, k); 

    return 0;
}
Output:
The kth largest element is: 7
  • Time Complexity: O(nlogn)
  • Space Complexity: O(1)

Approach 2: Using Set data structure.

The set data structure is used to store unique elements same type in sorted order. As mentioned in the question itself that all elements are distinct which means if we store them in a set data structure we can easily find the kth largest element.

C++ Code Implementation:
//C++ code to find kth largest element of an array using set
#include<bits/stdc++.h>
using namespace std;

//function to return kth largest element
int largestNumber(int arr[], int n, int k){
    //set data structure
    set<int> s(arr, arr+n);
    //pointer to first element
    set<int>::iterator it = s.begin();
    advance(it, n-k);

    return *it;
}

int main(){
    
    int arr[] = {4, 9, 2, 7, 3, 10};
    //size of given array
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 2;
    cout<<"The kth largest element is: "<<largestNumber(arr, n, k); 

    return 0;
}
Output:
The kth largest element is: 9

String Class in C++

Many people get confused with the definition of string in C++ whether it is a class or a data type. Let's make it clear that string is not a built-in data type but its behavior is very much similar to the fundamental data types.

String Class in C++

A String is a class from the standard template library that defines objects and is used to store a sequence of variable-length characters surrounded by double quotes(" ") that end with a null character '\0'. 

We use String data type to store words or a sentence kind of data.

  • Example 1: "Algolesson"
  • Example 2: "We are learning C++ Programming"

Note: All the functionality that we need to work with String class is available in the <string> header file so it is good practice to include this header file while working with String.


Some important properties of String:

  • In string, memory allocation takes place dynamically at runtime so no memory is wasted.
  • String implementations are slower than character arrays.
  • String provides several inbuilt functionalities that we can use to perform operations on strings.


How do you Declare and Initialize a string in C++?

String declaration is very much like any other data type, we use the string keyword followed by string name (variable name) which is going to store our value. In the below example, str is the string name and the default initialization of this string is empty. 

ex: string str; //str is an empty string


There are multiple ways to initialize a string in C++ and below are a few examples:

String Initialization Examples Definition
string str; In this example, the string is empty which is a default Initialization whenever we create a string.
string str2(str1); In this example, we are copying the value of one string (str1) into another string (str2).
string str("algolesson"); In this example, the str string is copying the value of the string literal present in double quotes "algolesson".
string str = "algolesson"; In this example also, the str string is copying the value of the string literal present in double quotes "algolesson".
string str(n, 'e'); In this example also, we initialize the string with n copies of the character 'e'.

C++ Code for string declaration and Initialization.

//C++ Code example for initialization
#include<iostream>
#include<string>
using namespace std;

int main(){

    string str1; //empty string
    string str2 ("What is your name?");
    string answer = "My name is John";
    str1 = "I am a Software Engineer.";
    string copyChar (3, 'w');
    string companyName (".algolesson.com");

    //Printing the string values
    cout<<str2<<endl;
    cout<<answer<<" "<<str1<<endl;
    cout<<copyChar<<companyName<<endl;

    return 0;
}
Output:
What is your name?
My name is John I am a Software Engineer.
www.algolesson.com

There are several operations that you can perform on String in C++ programming language. Let's understand each of them one by one. 

Read and Write Operations on String in C++ (getline()).

There are multiple ways to perform read/write operations on a string one is by using cin (character input) and cout (character output) objects but there is one limitation the cin can read only one word and everything after the white space is discarded. Let's understand with one example:
//C++ code to read and write string
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string str;
    //input from the user
    cout<<"Enter a string: ";
    cin>>str;
    cout<<str<<endl;

    return 0;
}
Output:
Enter a string: Hello World
Hello

If you observe in the above example, we entered a two-word string "Hello World" separated by white space but our string variable str is able to only the first word. To overcome this problem and to read an entire line of string we use the getline() standard library function which read the input one line at a time until the EOF(End of File) is encountered. 

Let's understand getline()in C++ with one example:
//C++ code to read and write string using getline()
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string name, subject;

    cout<<"What is your name? ";
    //use of getline() function
    getline(cin,name); 
    cout<<name<<endl;

    cout<<"Enter your subject name: ";
    //use of getline() function with delimiting character
    getline(cin,subject,'-'); 
    cout<<subject;
    
    return 0;
}
Output:
What is your name? I am John Wick
I am John Wick
Enter your subject name: Operating-System
Operating
In the above example code, we have taken user input using the getline() function, and when we use it for the first time (getline(cin, name)) we can observe that the entire line is displayed which means that getline() function capture characters even after white spaces. 

When we use the getline() function for the second time (getline(cin, subject, '-')) we have added a delimiting character (-) that is added as the third parameter of the function and it means that any character that appears after this delimiting character is discarded.

How to Access String Elements in C++?

String class is used to store a sequence of characters and each character takes one byte of memory. There are several ways to access individual characters of a string. 
String Function Definition
operator [pos] This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position (pos).
at() This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position.
back() This function is used to return a reference of the last character of the string. We can also add one character at the end using this function.
front() This function is used to return a reference of the first character of the string. We can also add one character at the front using this function.

Let's understand the ways of accessing characters in a string in C++ code:
/*C++ program to access string elements*/
#include<iostream>
#include<string>
using namespace std;

int main(){

  string str = "Welcome to Algolesson";
  //working of [] operator
  for(int i = 0; i < str.size(); i++){
    cout<<str[i];
  }
  //working of at()
  cout<<endl;
  for(int i = 0; i < str.size(); i++){
    cout<<str.at(i);
  }
  cout<<endl;
  //working of back()
  str.back() = '!';
  cout<<"The last character of the string is: "<<str.back()<<endl;
  //working of front()
  str.front() = '@';
  cout<<"The first  character of the string is: "<<str.front()<<endl;

  cout<<"String after operation: "<<str<<endl;
  return 0;
}
Output:
Welcome to Algolesson
Welcome to Algolesson
The last character of the string is: !
The first  character of the string is: @
String after operation: @elcome to Algolesso!



I hope you found this post useful, please write a comment if you found anything incorrect or share your valuable feedback. 

C++ Program to Check if a Year is a Leap Year.

In this post, you will learn to check whether a year is a leap year or not using the C++ programming language. But before moving to the coding part it is important to get some basic understanding of Leap Year. Let's start this topic with our first question and that is:


What is Leap Year?

A Year that contains 366 days is known as Leap Year. We get one leap year every four years and this year February month contains 29 days which is one extra day than any usual year. Examples of Leap Years: 1968, 2000, 2004, 2012, etc. 


How to Check if a Year is Leap Year or not?

There are certain conditions that you can check to find out whether a year is a leap year or not. 

  • If the given year is divisible by 400 then it is a leap year.
  • If the given year is divisible by 100 but not divisible by 400 then it is not a leap year.

  • If the given year is divisible by 4 but is not divisible by 100 then it is a leap year.
  • If both the above conditions fail to satisfy then the given year is not a leap year.

C++ Program to check Leap Year using if else statement.

//C++ Code to check Leap year using if else.
#include<iostream>
using namespace std;

int main(){

    int year;

    cout<<"Enter a Year: ";
    cin>>year;

    //Year divisible by 400
    if(year % 400 == 0)
       cout<<year<<" is a Leap Year.";
    //Year divisible by 100 but not divisible by 400   
    else if(year % 100 == 0)
       cout<<year<<" is not a Leap Year.";
    //Year divisible by 4 but not divisible by 100   
    else if(year % 4 == 0)
       cout<<year<<" is a Leap Year.";
    else
       cout<<year<<" is not a Leap Year.";

    return 0;            
}
Output:
Enter a Year: 1968
1968  is a Leap Year.


C++ Program to check Leap Year using nested if else statement.

//C++ Code to check Leap year using nested if else.
#include<iostream>
using namespace std;

int main(){

    int year;

    cout<<"Enter a Year: ";
    cin>>year;

    if(year % 4 == 0){
        if(year % 100 == 0){
            if(year % 400 == 0){
                cout<<year<<" is a Leap Year.";
            }
            else{
                cout<<year<<" is not a Leap Year.";
            }
        }
        else{
            cout<<year<<" is a Leap Year.";
        }
    }
    else{
        cout<<year<<" is not a Leap Year.";
    }

    return 0;            
}
Output:
Enter a Year: 2006
2006  is not a Leap Year.

Here in the above program, first, check if the year is divisible by 4 or not if not divisible then the given year is not a leap year. If the year is divisible by 4 then check if it is divisible by 100 or not, if not divisible by 100 then it is a leap year else, not a leap year. If the year is divisible by 100 then it must be divisible by 400 to be a leap year.

C++ Program to Check an Armstrong Number.

In this post, we will learn to check if a given number is Armstrong's number or not. Before checking any number we first need to understand what an Armstrong number is? Any positive n digits integer is called an Armstrong number of order n when the number can be expressed in the below format:

[abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + ...]

Here n = number of digit present.


Example of Armstrong Numbers.

Input: num = 153
Output: 153 is an Armstrong number.

Explanation: 
1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153

Input: num = 135
OutL 135 is not an Armstrong number.

Explanation: 1*1*1 + 3*3*3 + 5*5*5 = 1 + 27 + 125 = 153  135

Input: num = 1634
Output: 1634 is an Armstrong number.

Explanation: 
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 + 1296 + 81 + 256 = 1634

C++ Program to check three Digit Armstrong numbers.

//C++ code to check the three-digit Armstrong number.
#include<iostream>
using namespace std;

int main(){
    
    int num, numCopy, remainder, ans = 0;
    cout<<"Enter a three digit integer: ";
    cin>>num;
    numCopy = num;

    while(numCopy != 0){
        //this remainder always contain last digit
        remainder = numCopy % 10;

        ans += remainder * remainder * remainder;

        //remove the last digit of a number.
        numCopy /= 10;
    }
    
    if(ans == num)
       cout<<num<<" is an Armstrong Number.";
    else
       cout<<num<<" is not an Armstrong Number.";   
    return 0;                    
}
Output:
Enter a three digit integer: 153
153 is an Armstrong Number.
The above program can only check three-digit Armstrong numbers but if we get any integer with more digits then the above program will fail. (alert-warning) 

C++ Program to check n Digits Armstrong number.

//C++ code to check n digit Armstrong number.
#include<iostream>
#include<math.h>
using namespace std;

int main(){
    
    int num, numCopy, remainder, ans = 0;
    cout<<"Enter an integer: ";
    cin>>num;
    numCopy = num;
    
    //variable to store a number of digits
    int n = 0;
    //counting number of digits present given num 
    while(numCopy != 0){
        numCopy /= 10;
        n++;
    }
    numCopy = num;

    while(numCopy != 0){
        //this remainder always contain the last digit
        remainder = numCopy % 10;

        ans += round(pow(remainder, n));

        //remove the last digit of number.
        numCopy /= 10;
    }
    
    if(ans == num)
       cout<<num<<" is an Armstrong Number.";
    else
       cout<<num<<" is not an Armstrong Number.";   
    return 0;                    
}
Output:
Enter a three digit integer: 1634
1634 is an Armstrong Number.

The above program can check an Armstrong number with n number of digits and to do so we first need to count the number of digits present in the user input and store it in a variable n. This calculation is done by the first while loop in the program.
 
Next, while loop will check if the number is an Armstrong number or not, and for that, we will use the math pow(a, n) function which is present inside <math.h> header file.

C++ Code to Convert Celsius to Fahrenheit (vice versa).

In this post, we will learn to write C++ code to convert Celsius to Fahrenheit. We can use below conversion formula for our temperature calculation. Let's understand with one example.


Formula to calculate Fahrenheit when Celsius is given:

F = (C * 1.8) + 32

In the above mathematical formula, C stands for temperature given in Degree Celsius and F stands for the Degree Fahrenheit temperature we will get after the calculation. In most countries, Celsius is used to measuring the temperature but in US Fahrenheit is used to measure temperature.

Example: Find the degree Fahrenheit when the celsius temperature is 50°C.

F = (C * 1.8) + 32

  = (50 * 1.8) + 32

  = (90) + 32

  = 122°F(alert-passed)


C++ Code Implementation for Celsius to Fahrenheit conversion.

//C++ code to convert celsius to Fahrenheit
#include<iostream>
using namespace std;

int main(){
    float celsius, fahrenheit; 
   
    cout<<"Enter the temperature in Celsius: ";
    cin>>celsius;
    fahrenheit = (celsius * 1.8) + 32;
    cout<<"The temperature in Fahrenheit is: "<<fahrenheit;

    return 0;                    
}
Output:
Enter the temperature in Celsius: 50
The temperature in Fahrenheit is: 122

Converting Fahrenheit to Celsius.
We can also convert Fahrenheit to Celsius by deriving a new formula using the same above formula. We just did some basic math to create Fahrenheit to Celsius formula as shown below.

F = (C * 1.8) + 32

F - 32 = (C * 1.8)

(F - 32)/1.8 = C

C = (F - 32)/1.8

Example: Find the degree Celsius when the Fahrenheit temperature is 122°F.

C = (F - 32)/1.8

  = (122 - 32)/1.8

  = (90)/1.8

  = 50°F(alert-passed)

C++ Code Implementation for Fahrenheit to Celsius Conversion.

//C++ code to convert Fahrenheit to celsius
#include<iostream>
using namespace std;

int main(){
    float celsius, fahrenheit; 
   
    cout<<"Enter the temperature in Fahrenheit: ";
    cin>>fahrenheit;
    celsius = (fahrenheit - 32) / 1.8;
    cout<<"The temperature in Celsius is: "<<celsius;

    return 0;                    
}

Output:

Enter the temperature in Fahrenheit: 122
The temperature in Celsius is: 50

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson