Skip to content

Instantly share code, notes, and snippets.

@aliahmadcse
Last active December 3, 2020 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliahmadcse/76576cc302a4fcc3ff9ddd7c1824ec5f to your computer and use it in GitHub Desktop.
Save aliahmadcse/76576cc302a4fcc3ff9ddd7c1824ec5f to your computer and use it in GitHub Desktop.
Write a c++ function that splits the string X into an array bases on the delimeter character Y.
/**
* @author Ali Ahmad
* The program solves the following problem
*
* Write a c++ function that splits the string X into an array
* bases on the delimeter character Y.
* string* tokenizer(string X, char Y)
*
* Test cases:
* X: "1,2,3,4" Returns string array of size 4 with the elements
* Y: ',' {"1", "2", "3", "4"}
*
* X: "1,2, 4,5" Returns string array of size 2 with the elements
* Y: ' ' {"1,2,", "4,5"}
*
* X: "9:40:13" Returns string array of size 3 with the elements
* Y: ':' {"9", "40", "13"}
*/
#include <iostream>
using namespace std;
/**
* @return {int} count of delimeters in string s
* @param s {string} the string to check for delimeters
* @param delimeter {char} the character delimeter
*/
int getDelimeterCount(string s, char delimeter)
{
int count = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == delimeter)
{
count++;
}
}
return count;
}
/**
* @return {Pointer} a pointer to a string array
* containing splitted string based on delimeter y
*
* @param s {string}
* @param delimeter {char}
*/
string *tokenizer(string x, char y)
{
int delimeterCount = getDelimeterCount(x, y);
// delimter count is always less the size of array
string *arr = new string[delimeterCount + 1];
int arrIndex = 0;
int cutIndex = 0;
int delimeterPositionCount = 0;
int i = 0;
for (i = 0; i < x.length(); i++)
{
if (x[i] == y)
{
string subStr = x.substr(cutIndex, delimeterPositionCount);
cutIndex = i + 1;
delimeterPositionCount = 0;
arr[arrIndex++] = subStr;
}
else
{
delimeterPositionCount++;
}
}
// adding the last index
arr[arrIndex] = x.substr(cutIndex, delimeterPositionCount);
return arr;
}
int main()
{
string s = "9:40:13";
char delimeter = ':';
string *splittedString = tokenizer(s, delimeter);
// printing the array
int delimeterCount = getDelimeterCount(s, delimeter);
for (int i = 0; i < delimeterCount + 1; i++)
{
cout << splittedString[i] << ' ';
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment