Split String into Substrings of equal length in C++

In this artcile, we will discuss different ways to split a string into multiple substrings of equal lemnth in C++.

Table Of Contents

Introduction

There can be two variations for the given problem:
1. The number of substrings is given and we need to calculate the size of each substring for equal division.
2. The length of each substring is given, and we need to extract all substrings of that same length.

We will discuss both cases here:

Method 1: Using substr()

Case 1: When number of substrings is given in the input.

Advertisements

To split a string in C++ using substr() when the number of substrings is given in input, you can use the following approach:

  1. Read a string and an integer from the user.
  2. Calculate the length of the string.
  3. Calculate the length of each substring by dividing the length of the string by the number of substrings.
  4. Use a loop to iterate N (input integer) times.
  5. On each iteration of the loop, use the substr() function to extract a substring of length sub_length starting at the position current (i * sub_length in the string).
  6. Print the substring to the screen.
  7. Repeat steps 5 and 6 until all substrings have been extracted and printed.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    int num_substr;

    cout << "Enter a string: ";
    getline(std::cin, str);

    cout << "Enter the number of substrings: ";
    cin >> num_substr;

    int length = str.length();
    int sub_length = length / num_substr;

    for (int i = 0; i < num_substr; i ++) {
        cout << str.substr(i*sub_length, sub_length) << endl;
    }

    return 0;
}

Output

Enter a string: Hello, World!
Enter the number of substrings: 3
Hell
o, W
orld

Case 2: When the length of the substring is given in the input

To split a string in C++ using substr when the length of substrings is given in input, you can use the following approach:

  1. Initialize a string variable called input and take the input string
  2. Initialize an integer variable called sub_length to the desired length of each substring and take the input length.
  3. Calculate the number of substrings that the input string can be divided into by dividing the length of the input string by the substring length.
  4. Initialize a loop that will iterate n times.
  5. On each iteration of the loop, use the substr function to extract a substring of length sub_length starting at the current position (i * sub_length in the string).
  6. Print the substring to the screen.
  7. Repeat steps 5 and 6 until all substrings have been extracted and printed.

Program

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    int sub_length;

    cout << "Enter a string: ";
    getline(std::cin, str);

    cout << "Enter the size of substrings: ";
    cin >> sub_length;

    int length = str.length();
    int n = length / sub_length;

    for (int i = 0; i < n; i ++) {
        cout << str.substr(i*sub_length, sub_length) << endl;
    }

    return 0;
}

Output

Enter a string: Hello, World!
Enter the size of substrings: 4
Hell
o, W
orld

Time Complexity – O(N)

  • N is the length of the input string.

This is because the loop iterates over each character in the input string and performs a constant time operation (i.e., calling substr) on each character. The substr function itself has a time complexity of O(N), but since it is called once per character in the input string, the overall time complexity is O(N).

Note

Both approaches assume that the input string can be evenly divided into the desired number of parts. If this is not the case, some of the characters in the last will be left out considering only substrings of equal lengths are to be printed (as we can see above “!” has been left out).

Method 2: Using iterators

We can also use iterators to find all the substrings. Here we are using a hardcoded length = 4 for the substrings but as discussed above we can take input for either length or the number of substrings and calculate the other using the equation : number of substrings = (length of input string) / (length of each substring).

Algorithm

  1. Create a vector of strings called substrings. This will be used to store the resulting substrings.
  2. Create an iterator called it that will be used to iterate over the characters in the string.
  3. Initialize it to point to the first character in the string.
  4. Enter a loop that continues until it reaches the end of the string.
  5. Inside the loop, use the string constructor to create a new string that consists of the characters pointed to by it and the next length of characters. Also, add a check to make sure all substrings are equal to the input length and if not we leave that substring.
  6. Add the new string to the substrings vector.
  7. Advance it by input length.
  8. End the loop.
  9. Return the substrings vector.

Program

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> split_string(string str, int length) 
{
  vector<string> substrings;
  string::iterator it;
  for (it = str.begin(); it <= str.end(); it += length) 
  {
    if(it + length <= str.end())
    {
        substrings.push_back(string(it, it + length));
    }
  }
  return substrings;
}

int main() {
  string str = "Hello, World!";
  int length = 4;
  vector<string> substrings = split_string(str, length);
  for (string s : substrings) 
  {
    cout << s << endl;
  }
  return 0;
}

Output

Hell
o, W
orld

Time Complexity – O(N)

N is the length of the input string.
This is because the algorithm processes each character in the string once, so the time taken is directly proportional to the length of the string.

Note

Similar to the above approaches this also assumes that the input string can be evenly divided into the desired number of parts. If this is not the case, some of the characters in the last will be left out.

Summary

Today, we learned how to split a string into substrings of equal length in both cases where the length of the substring or the number of substrings is given using the substr() function and C++ iterators. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top