Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
Strings library
char_traits
classes:
string
global functions:
getline
operator+
operator<<
operator>>
comparison operators
swap
string
string::string
member constants:
string::npos
member functions:
string::append
string::assign
string::at
string::begin
string::capacity
string::clear
string::compare
string::copy
string::c_str
string::data
string::empty
string::end
string::erase
string::find
string::find_first_not_of
string::find_first_of
string::find_last_not_of
string::find_last_of
string::get_allocator
string::insert
string::length
string::max_size
string::operator+=
string::operator=
string::operator[]
string::push_back
string::rbegin
string::rend
string::replace
string::reserve
string::resize
string::rfind
string::size
string::substr
string::swap


string::substr

public member function
string substr ( size_t pos = 0, size_t n = npos ) const;

Generate substring

Returns a string object with its contents initialized to a substring of the current object.

This substring is the character sequence that starts at character position pos and has a length of n characters.

Parameters

pos
Position of a character in the current string object to be used as starting character for the substring.
If the position passed is past the end of the string, an out_of_range exception is thrown.
n
Length of the substring.
If this value would make the substring to span past the end of the current string content, only those characters until the end of the string are used.
npos is a static member constant value with the greatest possible value for an element of type size_t, therefore, when this value is used, all the characters between pos and the end of the string are used as the initialization substring.

Return Value

A string object containing a substring of the current object.

Example

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


generalities live in details.

Basic template member declarations

( basic_string<charT,traits,Allocator> )
1
2
typedef typename Allocator::size_type size_type;
basic_string substr (size_type pos =0, size_type n=npos) const;


See also