How to use substr() function in C++

The way to cut any portion from a string is called a sub-string. The substr() function exists in C++ to generate a new string by cutting a particular portion from a string. The string.h library file is required to include to use this function. This function has two arguments. The first argument contains the starting position of the new string, and the second argument contains the length of the string. The way to use the substr() function in C++ has been explained in this tutorial.

Pre-requisite

Before checking the examples of this tutorial, you have to check the g++ compiler is installed or not in the system. If you are using Visual Studio Code, then install the necessary extensions to compile the C++ source code to create the executable code. Here, the Visual Studio Code application has been used to compile and execute the C++ code.

Syntax

string substr (size_t pos = 0, size_t len = npos) const;

Here, the first argument contains the starting position from where the sub-string will be started, and the second argument contains the length of the sub-string. The function will return the sub-string if the valid starting position and length are given. The various uses of this function have shown in the next part of this tutorial.

Example 1: Simple use of substr()

The following example shows the most common and simple use of the substr() function. Create a C++ file with the following code to generate a substring from a string value. A string of multiple words has been assigned into a string variable. Next, the valid starting position and the length of the sub-string have in the argument values of the substr() function. Both the original string and the substring will be printed after executing the code.

//Include necessary libraries
//Include necessary libraries
#include
#include

int main () {
//Define a string variable
std::string originalstr="Welcome to Linuxhint";
//Cut the sub string using substr()
std::string newstr = originalstr.substr (11,9);
//Print the original string
std::cout <<"The original string is :" << originalstr << '\n';
//Print the sub string
std::cout <<"The substring is :" << newstr << '\n';

return 0;
}

Output: 

According to the code, the original string is ‘Welcome to LinuxHint‘. 11 has given as the starting position of the sub-string that is the position of the ‘L’ character, and 9 has given as the length value of the sub-string. ‘LinuxHint‘ has returned as the output of the substr() function after executing the code.

Example 2: Using substr() based on the position of a specific string 

The following code will generate the sub-string after searching the position of the particular string. Create a C++ file with the following code to test the code. A string value of the multiple words has been defined in the code. Next, the position of a particular string is searched in the main string by using the find() function. The substr() function has been used to generate the sub-string starting from the beginning of the string to the position value that will be returned by the find() function. 

//Include necessary libraries
#include
#include
//using namespace std;

int main ()
{
std::string strData = "I like C++ programming";

// Let's find the position of "--" using str.find()
int position = strData.find("programming");

// We'll get the substring until this pattern
std::string newstr = strData.substr(0, position);

std::cout << strData << '\n';
std::cout << newstr << '\n';

return 0;
}

Output:

According to the code, the main string value is, “I like C++ programming” and the value of the searching string is, ‘programming’ that exists in the main string. So, the output is, ‘I like C++‘ after executing the code.

Example 3: Using substr() with exception handling

The substr() function has been used with exception handling in the following code. The exception will be generated if the invalid starting position is given in the substr() function. Create a C++ file with the following code to test the code. In the try block, a string value of one word has been assigned, and an invalid starting position has been used in the substr() function that will raise an exception and print the error message. 

//Include necessary libraries
#include
#include

int main () {
try{

//Define a string variable
std::string originalstr="Linuxhint";
//Cut the sub string using substr()
std::string newstr = originalstr.substr (11,9);
//Print the sub string
std::cout <<"The substring is :" << newstr << '\n';
}
catch (const std::out_of_range) {
std::cerr << "The position is out of Range.\n";
}
return 0;
}

Output:

According to the code, the main string value is, “LinuxHint” and the starting position’s value is 11 that does not exist. So, the exception has been generated, and the error message has been printed after executing the code.

Example 4: Using substr() to split the string

The following example shows the use of the substr() function to split a string based on a delimiter. The find() function has been used to search the delimiter position, and the erase() function has been used to remove the splitted string with the delimiter from the main string. The ‘while’ loop has used to find all positions of the delimiter in the main string and store the splitted value into the vector array. Next, the values of the vector array have been printed.

//Include necessary libraries
#include
#include
#include

int main(){
//Define the string
std::string stringData = "PHP:C++:Python:";
//Define the separator
std::string separator = ":";
//Declare the vector variable
std::vector languages{};
//Declare integer variable
int position;
//Declare string variable
std::string outstr;
/*
Split the string using substr() function
and adding the splitted word into the vector
*/

while ((position = stringData.find(separator)) != std::string::npos) {
languages.push_back(stringData.substr(0, position));
stringData.erase(0, position + separator.length());
}
//Print all splitted words
for (const auto &outstr : languages) {
std::cout << outstr << std::endl;
}
return 0;
}

Output:

According to the code, the main string value is “PHP:C++:Python” and the value of the delimiter is, ‘:’. The following output will appear after executing the above script.

Conclusion

The main purpose of using the substr() function is to retrieve a substring from a string by mentioning the starting position and the length of the sub-string. The various uses of this function have been explained in this tutorial by using multiple examples to help the new C++ users to use it properly in their code.



from Linux Hint https://ift.tt/3kUKqqs

Post a Comment

0 Comments