C++ Program To Divide A String Into N Equal Parts - C++ Programming Tutorial
C++ Course / C++ Programs / C++ Program To Divide A String Into N Equal Parts

C++ Program To Divide A String Into N Equal Parts

BLUF: Mastering C++ Program To Divide A String Into N Equal Parts is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Program To Divide A String Into N Equal Parts

C++ is renowned for its efficiency. Learn how C++ Program To Divide A String Into N Equal Parts enables low-level control and high-performance computing in the tutorial below.

In this guide, you'll discover the process of dividing a string into N equal segments in C++. The C++ program leverages string manipulation and basic arithmetic to segment a string into N equal parts.

  1. Input:

Two user inputs are required at the beginning of the program:

  • A user-supplied string ( input ) that they desire to split into equal pieces.
  • The user can divide a string into as many equal pieces (N) as desired by providing an integer (n) to symbolize this.
  1. Length Calculation

Calculating the length of a string is essential in dividing it into equal segments. By utilizing the length method from the string class, the program determines the string's size and stores it in the variable len. This initial step is crucial for accurately dividing the string. Remember to validate for any potential errors before proceeding further.

The length of the string should be a multiple of n in order to divide it into uniform segments. The program checks if Len % n equals zero to determine this. If it does not, the program will terminate, showing an error message that the string cannot be divided into equal sections.

  1. Determining the Size of Each Segment:

When the string's length is a multiple of n, the software calculates the size of each segment. This is done by multiplying the length of the string by n to determine the value of partSize. Each segment should adhere to this specific size.

  1. Iteration for Division:

The n is the number of components that the user requested, and the loop iterates n times. Every time the loop is executed:

  • The program using the substr function of the string class to extracts a section of the input string. The substr function requires two inputs: the beginning position, which is updated after each iteration, and the length of the substring, which is partSize .
  • After that, the extracted part is included in a vector called "parts" that will hold all of the parts.
  1. Printing:

The software displays each segment of the text on individual lines following a successful division into equal sections. Subsequently, it presents a notification confirming the segmentation process.

  1. In Summary:

The program ultimately returns a value of 0 to indicate successful execution.

Program:

Let's consider an instance to showcase the process of splitting a string into N substrings in C++:

Example

#include <iostream>
#include <string>
#include <vector>
// Function to divide a string into N equal parts
std::vector<std::string> divideString(const std::string& input, int n) 
{
    int len = input.length(); 
    // Calculate the length of the input string
    std::vector<std::string> parts; 
    // Create a vector to store the parts
    // Check if it's possible to divide the string into equal parts
    if (len % n != 0) 
    {
        std::cout << "Cannot divide the string into equal parts." << std::endl;
        return parts; // Return an empty vector if not possible
    }
    int partSize = len / n; // Calculate the size of each part
    int startPos = 0;
    // Loop to extract each part of the string
    for (int i = 0; i < n; ++i)
    {
        std::string part = input.substr(startPos, partSize); // Use substr to extract a part
        parts.push_back(part); // Add the part to the vector
        startPos += partSize; // Update the starting position for the next part
    }
    return parts; // Return the vector containing the parts
}
int main() 
{
    std::string input;
    int n;
    // Input the string and the number of parts (N) from the user
    std::cout << "Enter a string: ";
    std::getline(std::cin, input); 
    // Read the entire input line
    std::cout << "Enter the number of parts (N): ";
    std::cin >> n;
    // Call the divideString function to divide the string into parts
    std::vector<std::string> parts = divideString(input, n);
    // Check if the division was successful
    if (!parts.empty())
    {
        std::cout << "The string is divided into " << n << " equal parts:" << std::endl;
        // Print each part of the string
        for (const std::string& part : parts) 
        {
            std::cout << part << std::endl;
        }
    }
    return 0;
}

Output:

Output

Enter a string: Ravan was killed by Rama
Enter the number of parts (N): 3
The string is divided into 3 equal parts:
Ravan wa
s killed
 by Rama

Explanation:

  • The divideString function Determines the input string's length (len). Ensures len% n == 0 to determine whether it is possible to divide the string into equal sections. Returns an empty vector (parts) and shows an error message if it is not feasible. Determines the partSize of each component. Extracts each component of the string using a loop and substr. Each part is added to the parts vector. Returns a vector of parts that includes the separated sections.
  • main Function Use std::getline to read the complete input line. Obtains from the user the number of pieces (n). Divide the string into pieces by using the divideString function. Upon success, distinct lines are printed for the total number of equal parts and each portion.
  • return 0 Returning 0 indicates that the program has run successfully.
  • Determines the input string's length (len).
  • Ensures len% n == 0 to determine whether it is possible to divide the string into equal sections.
  • Returns an empty vector (parts) and shows an error message if it is not feasible.
  • Determines the partSize of each component.
  • Extracts each component of the string using a loop and substr.
  • Each part is added to the parts vector.
  • Returns a vector of parts that includes the separated sections.
  • Use std::getline to read the complete input line.
  • Obtains from the user the number of pieces (n).
  • Divide the string into pieces by using the divideString function.
  • Upon success, distinct lines are printed for the total number of equal parts and each portion.
  • Returning 0 indicates that the program has run successfully.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience