(E) Splitting a string

Goal: I will practice using string and vector.

Instructions: Retrieve the code template: templates/04/split/ -> student/04/split/.

Implement the function split that splits the string given as a parameter into parts at the separators, and returns the parts stored in a vector. The parameters of the function are:

  1. a string that will be split
  2. a separator
  3. a boolean value revealing whether you want to ignore the empty parts (empty strings), the default is false. (If the aim is to ignore the empty parts, the value true is passed for the function.)

An empty part is created if there are two consecutive separators, or if a string starts or ends with a separator. For example, if the separator is : and the string is A:B::C: the parsed parts are ”A”, ”B”, ””, ”C,” and ””. If there are several consecutive separators, a new, empty part is created at each space with no characters. If you want to ignore the empty parts, then the function will not return the parts with no characters.

Add only the implementation of the function into the code template. Do not edit the main function in any way. When you have implemented the function, the main program is supposed to work like this:

Enter a string: a::bc:def::hijlkm
Enter the separator character: :
Splitted string including empty parts:
a

bc
def

hijlkm
Splitted string ignoring empty parts:
a
bc
def
hijlkm

Here you have an example that is a bit tougher to read. It includes spaces at the beginning and end of the split string, and as a separator:

Enter a string:    A B   C   D E
Enter the separator character:
Splitted string including empty parts:



A
B


C


D
E



Splitted string ignoring empty parts:
A
B
C
D
E

Tips for completing the assignment:

  • Recall default value parameters (or overloading) from section 2.5 Functions (The amount and types of parameters).
  • It is useful to review the material at 2.6 Strings and characters and especially the point ”Some useful string operations in C++”. You can use several methods from string library in the assignment.
  • You might want to separate the problem into sections in your mind, and then implement them one at a time. The sections of this assignment could be finding the separator and detecting a part.
  • If you end up with a solution where you examine the indexes of the string with a loop structure, use string::size_type as the type of your index variable, not int.
  • On several occasions, we have passed vector as a reference, not a value parameter, to a function. That way the code is more efficient. In this assignment, you might think of passing a reference to vector as the return value. DO NOT DO THAT! Remind yourself about what happens to local variables of a function when the execution of the function finishes.

A+ presents the exercise submission form here.