Split a string into substrings of equal length in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <vector> int main() { std::string str = "abcdefg"; int mid = (str.length() + 1) / 2; std::string first = str.substr(0, mid); std::string second = str.substr(mid); std::cout << first << std::endl; // abcd std::cout << second << std::endl; // efg return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> #include <vector> int main() { std::string str = "abcdefg"; auto mid = str.begin() + (str.size() + 1) / 2; std::string first(str.begin(), mid); std::string second(mid, str.end()); std::cout << first << std::endl; // abcd std::cout << second << std::endl; // efg return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <string> #include <iterator> #include <regex> int main() { std::string str = "abcdefg"; int n = (str.length() + 1) / 2; // Create a regular expression pattern that matches any n characters std::regex pattern(".{0," + std::to_string(n) + "}"); // Use a loop to iterate over the matches of the pattern in the string // using regex_iterator auto it = std::sregex_iterator(str.begin(), str.end(), pattern); while (it != std::sregex_iterator()) { // display each match as a substring std::cout << it->str() << std::endl; it++; } return 0; } |
That’s all about splitting a string into substrings of equal length in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)