Cpp substr string std

std::string substr() method

Returns a substring [ pos, pos + count ).
If the requested substring extends past the end of the string, i.e. count is greater than size() — pos (e.g. if count == npos ), the returned substring is [ pos, size() ).

Parameters​

Return value​

String containing the substring [ pos, pos + count ) or [ pos, size() ).

Complexity​

Linear in count — O(count).

Exceptions​

Notes​

The returned string is constructed as if by basic_string(data() + pos, count) , which implies that the returned string’s allocator will be default-constructed — the new allocator might not be a copy of get_allocator() .

Example​

#include  #include   int main()   std::string a = "0123456789abcdefghij";  // count is npos, returns [pos, size())  std::string sub1 = a.substr(10);  std::cout < sub1  <'\n';  // both pos and pos+count are within bounds, returns [pos, pos+count)  std::string sub2 = a.substr(5, 3);  std::cout < sub2  <'\n';  // pos is within bounds, pos+count is not, returns [pos, size())  std::string sub4 = a.substr(a.size()-3, 50); // this is effectively equivalent to // std::string sub4 = a.substr(17, 3); // since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3  std::cout < sub4  <'\n';  try   // pos is out of bounds, throws  std::string sub5 = a.substr(a.size()+3, 50);  std::cout < sub5  <'\n'; > catch(const std::out_of_range& e)   std::cout  <"pos exceeds string size\n"; > > 

Источник

std:: string::substr

Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).

Parameters

pos Position of the first character to be copied as a substring.
If this is equal to the string length, the function returns an empty string.
If this is greater than the string length, it throws out_of_range.
Note: The first character is denoted by a value of 0 (not 1).
len Number of characters to include in the substring (if the string is shorter, as many characters as possible are used).
A value of string::npos indicates all characters until the end of the string.
size_t is an unsigned integral type (the same as member type string::size_type ).

Return Value

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// string::substr int main () < std::string str="We think in generalities, but we live in details."; // (quoting Alfred N. Whitehead) std::string str2 = str.substr (3,5); // "think" std::size_t pos = str.find("live"); // position of "live" in str std::string str3 = str.substr (pos); // get from "live" to the end std::cout ' ' '\n'; return 0; >

Complexity

Iterator validity

Data races

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the string.

If pos is greater than the string length, an out_of_range exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also

string::replace Replace portion of string (public member function) string::data Get string data (public member function) string::find Find content in string (public member function) string::assign Assign content to string (public member function) string::string Construct string object (public member function)

Источник

C++ String Library — substr

It returns a newly constructed string object with its value initialized to a copy of a substring of this object.

Declaration

Following is the declaration for std::string::substr.

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

C++11

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

C++14

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

Parameters

  • str − It is a string object.
  • len − It is used to copy the characters.
  • pos − Position of the first character to be copied.

Return Value

It returns a string object with a substring of this object.

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::substr.

The sample output should be like this −

Annual Membership

Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

Training for a Team

Affordable solution to train a team and make them project ready.

Tutorials PointTutorials Point

  • About us
  • Refund Policy
  • Terms of use
  • Privacy Policy
  • FAQ’s
  • Contact

Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.

We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Источник

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.

//Define a string variable
std :: string originalstr = «Welcome to Linuxhint» ;

//Cut the sub string using substr()
std :: string newstr = originalstr. substr ( 11 , 9 ) ;

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.

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 ) ;

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.

//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 }
catch ( const std :: out_of_range ) {

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.

//Define the string
std :: string stringData = «PHP:C++:Python:» ;

//Define the separator
std :: string separator = «:» ;

//Declare the vector variable
std :: vector < std :: string >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 ( ) ) ;
}

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.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Читайте также:  Css text glow effects
Оцените статью