In this C++ tutorial, you will learn how to extract a substring from a std::string using std::string::substr(). The examples cover a start index and length, extracting from an index to the end, using start and end positions, handling out-of-range indexes, getting the last characters, and extracting text around a delimiter.

C++ substring with std::string::substr()

A substring is a consecutive sequence of characters taken from a string. In C++, the usual way to create one from a std::string is the substr() member function. You can also copy characters manually with a loop when you need custom processing.

Syntax of substr() function

substr() is a member function of std::string class. The following is the syntax of substr() function.

</>
Copy
substr (pos, len)
  • substr() function is called on a string object.
  • pos is the starting position or index of substring in this string. The default value of pos is zero. If pos is not specified, then the whole string is returned as substring.
  • len is the number of characters in the substring. len is optional. If len is not specified, the substring till the end of this string is returned.

substr() returns a newly formed string object representing the substring formed using this string, pos and len.

The important detail is that the second argument is a character count, not an ending index. For example, str.substr(5, 10) means “start at index 5 and copy up to 10 characters.” If fewer than 10 characters remain, C++ copies only the characters available up to the end of the string.

Index rules for C++ substr()

  • C++ string indexes are zero-based, so the first character is at index 0.
  • If pos < str.size(), extraction starts at that character.
  • If pos == str.size(), substr() returns an empty string.
  • If pos > str.size(), std::out_of_range is thrown.
  • If len is larger than the number of characters remaining, the substring simply ends at the end of the original string.

C++ substring examples

1. Find substring with start position and length

In this example, we take a string with some initial value and find the substring of this string starting at given starting position and spanning a specified length.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   int pos = 5;
   int len = 10;
   string substring = str1.substr(pos, len);

   cout << substring;
}

Output

e changing

Note: If the requested length extends past the end of the original string, substr() returns only the characters that remain. The len variable itself is not modified.

2. Find substring with only start position

In this example, we take a string with some initial value and find the substring of this string starting at given starting position. We do not provide the length of substring. The returned substring should span from start position provided till the end of the this string.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   int pos = 5;
   string substring = str1.substr(pos);

   cout << substring;
}

Output

e changing the world.

This is the standard pattern for a C++ substring from an index to the end: call substr(pos) and omit the length argument.

3. Find substring with no start position

In this example, we take a string with some initial value and find the substring of this string. We do not provide the start position of the substring. The returned string should be a copy of the original string.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   string substring = str1.substr();

   cout << substring;
}

Output

We are changing the world.

4. Find substring with start position and end position

In this example, we take a string with some initial value and find the substring of this string starting at given starting position and ending at a given ending position.

substr() does not accept an ending index directly. It accepts a starting position and a character count, so we calculate the required length from the start and end positions.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   int start = 5;
   int end = 12;
   string substring = str1.substr(start, end - start + 1);

   cout << substring;
}

Output

e changi

Here, end is treated as an inclusive ending index. Therefore, the character count is end - start + 1. If your ending position is exclusive instead, use end - start.

5. Find substring using For loop

In this example, we shall find the substring of a string, given start position and length of the substring, using C++ For Loop.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   int start = 5;
   int len = 10;

   char substring[len+1];

   for(int i=0; i < len; i++) {
      substring[i] = str1[start + i];
   }

   //end string
   substring[len] = '\0';

   cout << substring;
}

Output

e changing

Portability note: The declaration char substring[len+1] in this existing example is a variable-length array. Variable-length arrays are not part of standard C++, although some compilers support them as an extension. For portable C++ code, prefer std::string::substr() or a standard container when the size is known only at runtime.

Similarly, you can use C++ While Loop or C++ Do-While Loop to find the substring.

For ordinary std::string work, prefer substr(). A manual loop is mainly useful when you want to inspect, transform, or filter characters while copying them.

6. Find substring with start position out of range

If the starting position passed to substr() is greater than the string size, the function throws std::out_of_range at runtime.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   string str1 = "We are changing the world.";
   
   int start = 50;
   int len = 10;

   string substring = str1.substr(start, len);

   cout << substring;
}

Output

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 50) > this->size() (which is 26)

The exact exception message is implementation-dependent, but the rule is the same: pos may equal size(), but it must not be greater than size(). If the index comes from user input or a calculation, validate it before calling substr().

7. Get the last 4 characters of a C++ string

To extract the last n characters, start at str.size() - n. Check the length first so that unsigned subtraction does not underflow when the string is shorter than n.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "ABCD1234";
    size_t count = 4;

    if (str.size() >= count) {
        cout << str.substr(str.size() - count);
    }
}

Output

1234

8. Extract a C++ substring until a delimiter

substr() extracts by position, while find() locates a character or text. Combining them is useful for delimiter-based strings. The following example extracts everything before the first colon.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "name:TutorialKart";
    size_t delimiter = text.find(':');

    if (delimiter != string::npos) {
        string key = text.substr(0, delimiter);
        cout << key;
    }
}

Output

name

To extract the text after the delimiter, start one character after it:

</>
Copy
string value = text.substr(delimiter + 1);

9. Find a substring before extracting it

substr() does not search for text. If you need to determine whether one string occurs inside another, use find(). When find() succeeds, it returns the starting index; otherwise it returns std::string::npos.

</>
Copy
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Learn C++ substring";
    string word = "substring";

    size_t pos = text.find(word);

    if (pos != string::npos) {
        cout << text.substr(pos, word.length());
    }
}

Output

substring

substr() behavior to remember

For a string named str, these common forms cover most substring tasks:

</>
Copy
str.substr();              // copy the whole string
str.substr(pos);           // from pos to the end
str.substr(pos, count);    // at most count characters
str.substr(0, end);        // from the beginning to an exclusive end index

Creating a substring constructs a new std::string containing the selected characters. In typical implementations, the work is proportional to the number of characters copied, so repeatedly creating large substrings inside performance-sensitive loops can add avoidable copying.

C++ substring editorial QA checklist

  • Confirm every example treats the second substr() argument as a character count, not an ending index.
  • Check that all positions are described as zero-based indexes.
  • For “to the end” examples, verify the length argument is omitted rather than guessed.
  • When using find(), check for std::string::npos before passing the result to substr().
  • For last-n-character examples, verify the string length before calculating size() - n.
  • When showing invalid positions, distinguish pos == size() (valid, empty result) from pos > size() (throws std::out_of_range).

C++ substring summary

In this C++ Tutorial, we learned how to find substring of a string in C++ with the help of example programs.