C++ string substr()

Common member function

< string>

std::string::substr

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

Produce substring
Returns a new one
A copy of the String object that is initialized to a substring of the String object.

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

parameter

pos

The position of the first character is copied as a substring.

this function returns an empty string if this is equal to the length of the string.

if this is greater than the length of the string, it will throw out_of_range.

note: the first character is represented as the value 0 (not 1).

len

The number of characters included in the subscript (if the string is short, as many characters as possible can be used as needed).

string :: non-profit value represents all characters up to the end of the string.

size_t is an unsigned integral type (the same as member type)
string::size_type).

The return value A
String Object with a substring of this object.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// string::substr
#include <iostream>
#include <string>

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 << str2 << ' ' << str3 << '\n';

  return 0;
}
 

Output:

think live in details.


Read More: