Project 2

Some languages, such as Python, can split a string on a specified delimiter character and return a list of strings. The delimiter is dropped. Write a program that can accomplish this.

This should be a function but we have not yet covered subprograms, so you may write a monolithic program. If you wish to look ahead, write this as a function.

Hint: a vector would be a good data structure. It is close to a “list” in Python.

Print the result in Python format,

[sub1,sub2,sub3]
Sample solution

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

using namespace std;

int main() {

    string input="Sample ;string ;for ; this; project \n";
    char delimiter;
    delimiter=';';

    string element;
    vector<string> output;

    for (char ch : input) {
        if (ch == delimiter) {
            output.push_back(element);
            element="";
        }
        element+=ch;
    }
    //Add in the last one
    output.push_back(element);

    for (int i=0;i<output.size();++i){
       cout<<output[i];
    }

    return 0;
}

   

Previous
Next