This post will discuss how to split a string into substrings of equal length in C++.

1. Using string::substr function

The substr() function is one of the simplest and most straightforward methods to split a string into substrings of equal length. It returns a copy of a substring of the string, starting from a given position and having a given length. It takes one or two parameters: the position of the first character of the substring, and optionally, the length of the substring. It can be used as follows to split a string into substrings of equal length:

Download  Run Code

2. Using std::string constructor

Alternatively, we can use the range constructor of std::string to split a string into substrings of equal length. For example:

Download  Run Code

3. Using Regular Expressions

To split a string into substrings of equal length, we can create a regular expression pattern that matches any n characters in the string, where n is the number of substrings. Then, we can use a loop to iterate over the matches of the pattern in the string using regex_iterator and track each match as a substring. For example:

Download  Run Code

That’s all about splitting a string into substrings of equal length in C++.