This demo illustrates basic std::string operations by creating
several useful utility functions.
Strings.h
#pragma once
/////////////////////////////////////////////////////////////////
// Strings.h - string utility functions //
// //
// Jim Fawcett, CSE687 - Object Oriented Design, Summer 2017 //
/////////////////////////////////////////////////////////////////
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
/*--- remove whitespace from front and back of string argument ---*/
template <typename T>
std::basic_string<T> trim(const std::basic_string<T>& toTrim)
{
std::basic_string<T> temp;
std::locale loc;
std::basic_string<T>::const_iterator iter = toTrim.begin();
while (isspace(*iter, loc))
{
++iter;
}
std::basic_string<T>::const_iterator itEnd = toTrim.end();
for (; iter != toTrim.end(); ++iter)
{
temp += *iter;
}
std::basic_string<T>::reverse_iterator riter;
size_t pos = temp.size();
for (riter = temp.rbegin(); riter != temp.rend(); ++riter)
{
--pos;
if (!isspace(*riter, loc))
{
break;
}
}
temp.erase(++pos);
return temp;
}
/*--- split sentinel separated strings into a vector of trimmed strings ---*/
template <typename T>
std::vector<std::basic_string<T>> split(const std::basic_string<T>& toSplit, T splitOn = ',')
{
std::vector<std::basic_string<T>> splits;
std::basic_string<T> temp;
std::basic_string<T>::const_iterator iter;
for(iter=toSplit.begin(); iter !=toSplit.end(); ++iter)
{
if(*iter != splitOn)
{
temp += *iter;
}
else
{
splits.push_back(trim(temp));
temp.clear();
}
}
if (temp.length() > 0)
splits.push_back(trim(temp));
return splits;
}
/*--- display vector of split strings, each on its own line ---*/
template <typename T>
void showSplits(const std::vector <std::basic_string<T>>& toSplit);
template<>
void showSplits(const std::vector<std::string>& splits)
{
for (auto line : splits)
{
std::cout << "\n \"" << line << "\"";
}
std::cout << "\n";
}
template<>
void showSplits(const std::vector<std::wstring>& splits)
{
for (auto line : splits)
{
std::wcout << L"\n L\"" << line << L"\"";
}
std::wcout << L"\n";
}
/*--- show enquoted string ---*/
void showString(const std::string& str);
void showString(const std::wstring& str);