C++ Tokenize a string with spaces and quotes - c++

I would like to write something in C++ that tokenize a string. For the sake of clarity, consider the following string:
add string "this is a string with spaces!"
This must be split as follows:
add
string
this is a string with spaces!
Is there a quick and standard-library-based approach?

No library is needed. An iteration can do the task ( if it is as simple as you describe).
string str = "add string \"this is a string with space!\"";
for( size_t i=0; i<str.length(); i++){
char c = str[i];
if( c == ' ' ){
cout << endl;
}else if(c == '\"' ){
i++;
while( str[i] != '\"' ){ cout << str[i]; i++; }
}else{
cout << c;
}
}
that outputs
add
string
this is a string with space!

I wonder why this simple and C++ style solution is not presented here.
It's based on fact that if we first split string by \", then each even chunk is "inside" quotes, and each odd chunk should be additionally splitted by whitespaces.
No possibility for out_of_range or anything else.
unsigned counter = 0;
std::string segment;
std::stringstream stream_input(input);
while(std::getline(stream_input, segment, '\"'))
{
++counter;
if (counter % 2 == 0)
{
if (!segment.empty())
std::cout << segment << std::endl;
}
else
{
std::stringstream stream_segment(segment);
while(std::getline(stream_segment, segment, ' '))
if (!segment.empty())
std::cout << segment << std::endl;
}
}

Here is a complete function for it. Modify it according to need, it adds parts of string to a vector strings(qargs).
void split_in_args(std::vector<std::string>& qargs, std::string command){
int len = command.length();
bool qot = false, sqot = false;
int arglen;
for(int i = 0; i < len; i++) {
int start = i;
if(command[i] == '\"') {
qot = true;
}
else if(command[i] == '\'') sqot = true;
if(qot) {
i++;
start++;
while(i<len && command[i] != '\"')
i++;
if(i<len)
qot = false;
arglen = i-start;
i++;
}
else if(sqot) {
i++;
start++;
while(i<len && command[i] != '\'')
i++;
if(i<len)
sqot = false;
arglen = i-start;
i++;
}
else{
while(i<len && command[i]!=' ')
i++;
arglen = i-start;
}
qargs.push_back(command.substr(start, arglen));
}
for(int i=0;i<qargs.size();i++){
std::cout<<qargs[i]<<std::endl;
}
std::cout<<qargs.size();
if(qot || sqot) std::cout<<"One of the quotes is open\n";
}

The Boost library has a tokenizer class that can accept an escaped_list_separator. The combination of these look like they might provide what you are looking for.
Here are links to the boost documentation, current as of this post and almost certainly an old version by the time you read this.
https://www.boost.org/doc/libs/1_73_0/libs/tokenizer/doc/tokenizer.htm
https://www.boost.org/doc/libs/1_73_0/libs/tokenizer/doc/escaped_list_separator.htm
This example is stolen from the boost documentation. Forgive me for not creating my own example.
// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>
int main(){
using namespace std;
using namespace boost;
string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
tokenizer<escaped_list_separator<char> > tok(s);
for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg){
cout << *beg << "\n";
}
}

I would define a class Token to read a single token from a stream.
Then using your code becomes very trivial.
#include <iostream>
#include <string>
int main()
{
// Simply read the tokens from the stream.
Token t;
while(std::cin >> t)
{
std::cout << "Got: " << t << "\n";
}
}
Stream objects like this are very easy to write:
class Token
{
// Just something to store the value in.
std::string value;
// Then define the input and output operators.
friend std::ostream& operator<<(std::ostream& str, Token const& output)
{
return str << output.value;
}
// Input is slightly harder than output.
// but not that difficult to get correct.
friend std::istream& operator>>(std::istream& str, Token& input)
{
std::string tmp;
if (str >> tmp)
{
if (tmp[0] != '"')
{
// We read a word that did not start with
// a quote mark. So we are done. Simply put
// it in the destination.
input.value = std::move(tmp);
}
else if (tmp.front() == '"' && tmp.back() == '"')
{
// we read a word with both open and close
// braces so just nock these off.
input.value = tmp.substr(1, tmp.size() - 2);
}
else
{
// We read a word that has but has a quote at the
// start. So need to get all the characters upt
// closing quote then add this to value.
std::string tail;
if (std::getline(str, tail, '"'))
{
// Everything worked
// update the input
input.value = tmp.substr(1) + tail;
}
}
}
return str;
}
};

I guess there is no straight forward approach with standard library. Indirectly following algo will work:
a) search for '\"' with string::find('\"') . If anything found search for next '\"' using string::find('\'',prevIndex), If found use string::substr(). Discard that part from the original string.
b) Now Serach for ' ' character in the same way.
NOTE: you have to iterate through the whole string.

Here is my solution, it's equivalent to python's shlex, shlex_join() is the inverse of shlex_split():
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <utility>
#include <vector>
// Splits the given string using POSIX shell-like syntax.
std::vector<std::string> shlex_split(const std::string& s)
{
std::vector<std::string> result;
std::string token;
char quote{};
bool escape{false};
for (char c : s)
{
if (escape)
{
escape = false;
if (quote && c != '\\' && c != quote)
token += '\\';
token += c;
}
else if (c == '\\')
{
escape = true;
}
else if (!quote && (c == '\'' || c == '\"'))
{
quote = c;
}
else if (quote && c == quote)
{
quote = '\0';
if (token.empty())
result.emplace_back();
}
else if (!isspace(c) || quote)
{
token += c;
}
else if (!token.empty())
{
result.push_back(std::move(token));
token.clear();
}
}
if (!token.empty())
{
result.push_back(std::move(token));
token.clear();
}
return result;
}
// Concatenates the given token list into a string. This function is the
// inverse of shlex_split().
std::string shlex_join(const std::vector<std::string>& tokens)
{
auto it = tokens.begin();
if (it == tokens.end())
return {};
std::ostringstream oss;
while (true)
{
if (it->empty() || it->find_first_of(R"( "\)") != std::string::npos)
oss << std::quoted(*it);
else
oss << *it;
if (++it != tokens.end())
oss << ' ';
else
break;
}
return oss.str();
}
void test(const std::string& s, const char* expected = nullptr)
{
if (!expected)
expected = s.c_str();
if (auto r = shlex_join(shlex_split(s)); r != expected)
std::cerr << '[' << s << "] -> [" << r << "], expected [" << expected << "]\n";
}
int main()
{
test("");
test(" ", "");
test("a");
test(" a ", "a");
test("a b", "a b");
test(R"(a \s b)", "a s b");
test(R"("a a" b)");
test(R"('a a' b)", R"("a a" b)");
test(R"(a \" b)", R"(a "\"" b)");
test(R"(a \\ b)", R"(a "\\" b)");
test(R"("a \" a" b)");
test(R"('a \' a' b)", R"("a ' a" b)");
test(R"("a \\ a" b)");
test(R"('a \\ a' b)", R"("a \\ a" b)");
test(R"('a \s a' b)", R"("a \\s a" b)");
test(R"("a \s a" b)", R"("a \\s a" b)");
test(R"('a \" a' b)", R"("a \\\" a" b)");
test(R"("a \' a" b)", R"("a \\' a" b)");
test(R"("" a)");
test(R"('' a)", R"("" a)");
test(R"(a "")");
test(R"(a '')", R"(a "")");
}

There is a standard-library-based approach in C++14 or later. But it is not quick.
#include <iomanip> // quoted
#include <iostream>
#include <sstream> // stringstream
#include <string>
using namespace std;
int main(int argc, char **argv) {
string str = "add string \"this is a string with spaces!\"";
stringstream ss(str);
string word;
while (ss >> quoted(word)) {
cout << word << endl;
}
return 0;
}

Related

How can i split adjacent numbers and letters in c++?

I've got a large text document that including adjacent numbers and letters.
Just like that,
JACK1940383DAVID30284HAROLD68372TROY4392 etc.
How can i split this like below in C++
List: Jack / 1940383 , David/30284, ...
You can use std::string::find_first_of() and std::string::find_first_not_of() in a loop, using std::string::substr() to extract each piece, eg:
std::string s = "JACK1940383DAVID30284HAROLD68372TROY4392";
std::string::size_type start = 0, end;
while ((end = s.find_first_of("0123456789", start)) != std::string::npos) {
std::string name = s.substr(start, end-start);
start = end;
int number;
if ((end = s.find_first_not_of("0123456789", start)) != std::string::npos) {
number = std::stoi(s.substr(start, end-start));
}
else {
number = std::stoi(s.substr(start));
}
start = end;
// use name and number as needed...
}
Online Demo
You can use regex like this:
#include <iostream>
#include <string>
#include <regex>
#include <vector>
// create a struct to group your data
// this makes it easy to store it in a vector.
struct person_t
{
std::string name;
std::string number;
};
// overloaded output operator for printing one person's details
std::ostream& operator<<(std::ostream& os, const person_t& person)
{
std::cout << person.name << ": " << person.number << std::endl;
return os;
}
// get a vector of person_t based on the input
auto get_persons(const std::string& input)
{
// make a regex in this case a regex that will match one or more capital letters
// and groups them using the ()
// then match one or more digits and group them too.
static const std::regex rx{ "([A-Z]+)([0-9]+)" };
std::smatch match;
// a vector to hold all the persons
std::vector<person_t> persons;
// start at begin of string and look for first part of the string
// that matches the regex.
auto cbegin = input.cbegin();
while (std::regex_search(cbegin, input.cend(), match, rx))
{
// match[0] will contain the whole match,
// match[1]-match[n] will contain the groups from the regular expressions
// match[1] will contain the match with characters and thus the name
// match[2] will contain the match with the numbers and thus the number.
// create a person_t struct with this info
person_t person{ match[1], match[2] };
// and add it to the vector
persons.push_back(person);
cbegin = match.suffix().first;
}
return persons;
}
int main()
{
// parse and split the string
auto persons = get_persons("JACK1940383DAVID30284HAROLD68372TROY4392");
// show the output
for (const auto& person : persons)
{
std::cout << person;
}
}
As pointed in other good answers you can use
find_first_of(), find_first_not_of() and substr() from std::string in a loop
regex
But it may be too much. I will add 3 more examples that you may find
simpler.
The first 2 programs expects the file name on the command line for (my) convenience here, and the test file is in.txt. Contents are the same as posted
JACK1940383DAVID30284HAROLD68372TROY4392
The last example just parses the string data declared as a char[]
1. Using fscanf()
Since the target is to consume formatted data, fscanf() is an option. As the data structure is very simple, the program is just a one line loop:
char mask[] = "%50[^0-9]%50[0-9]";
while ( 2 == fscanf(F, mask, tk_key, tk_value))
std::cout << tk_key << "/" << tk_value << "\n";
program output
output is the same for all examples
JACK/1940383
DAVID/30284
HAROLD/68372
TROY/4392
code for ex. 1
#include <errno.h>
#include <iostream>
int main(int argc,char** argv)
{
if (argc < 2)
{ std::cerr << "Use: pgm FileName\n";
return -1;
}
FILE* F = fopen(argv[1], "r");
if (F == NULL)
{
perror("Could not open file");
return -1;
}
std::cerr << "File: \"" << argv[1] << "\"\n";
char tk_key[50], tk_value[50];
char mask[] = "%50[^0-9]%50[0-9]";
while ( 2 == fscanf(F, mask, tk_key, tk_value))
std::cout << tk_key << "/" << tk_value << "\n";
fclose(F);
return 0;
}
using a state machine
There are just 2 states so it is not a fancy FSA ;) State machines are good for representing this kind of stuff, albeit here this seems to be overkill.
#define S_LETTER 0
#define S_DIGIT 1
#include <algorithm>
#include <iostream>
#include <fstream>
using iich = std::istream_iterator<char>;
int main(int argc,char** argv)
{
std::ifstream in_file{argv[1]};
if ( not in_file.good()) return -1;
iich p {in_file}, eofile{};
std::string token{}; // string to build values
char st = S_LETTER; // state value for FSA
std::for_each(p, eofile,
[&token,&st](char ch)
{
char temp = 0;
switch (st)
{
case S_LETTER:
if ((ch >= '0') && (ch <= '9'))
{
std::cout << token << "/";
token = ch;
st = S_DIGIT; // now in number
}
else token += ch; // concat in string
break;
case S_DIGIT:
default:
if ((ch < '0') || (ch > '9'))
{ // is a letter
std::cout << token << "\n";
token = ch;
st = S_LETTER; // now in name
}
else token += ch; // concat in string
break;
}; // switch()
});
std::cout << token << "\n"; // print last token
}
Here we have no loop. for_each gets the data from an iterator and passes it to a function that builds the name and the value as strings and couts them
Output is the same
3. a simple FSA to consume the data
#define S_LETTER 0
#define S_DIGIT 1
#include <iostream>
int main(void)
{
char one[] = "JACK1940383DAVID30284HAROLD68372TROY4392";
char* p = (char*)&one;
char* token = p;
char st = S_LETTER;
char temp = 0;
while (*p != 0)
{
switch (st)
{
case S_LETTER:
if ((*p >= '0') && (*p <= '9'))
{
temp = *p;
*p = 0;
std::cout << token << "/";
*p = temp;
token = p;
st = S_DIGIT; // now in number
}
break;
case S_DIGIT:
default:
if ( (*p < '0') || (*p > '9'))
{ // letter
temp = *p;
*p = 0;
std::cout << token << "\n";
*p = temp;
token = p;
st = S_LETTER; // now in name
}
break;
}; // switch()
p += 1; // next symbol
}; // while()
std::cout << token << "\n"; // print last token
}
This code just uses a C-style loop to parse the input data

Find second to last word in a string C++

Hi I need to find second to last word in a string. Right now below program is printing the last one.
#include <iostream>
#include <string>
using namespace std;
int main() {
string text{"some line with text"};
// find last space, counting from backwards
int i = text.length() - 2; // last character
while (i != 0 && !isspace(text[i]))
{
--i;
}
string lastword = text.substr(i+1); // +1 to skip leading space
cout << lastword << endl;
return 0;
}
Output: (Printing last word)
text
You can split the string into words and hold the previous word before saving the current word.
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string text{"some line with text"};
std::stringstream ss(text);
std::string previousword, lastword, newword;
while (ss >> newword) {
previousword = lastword;
lastword = newword;
}
std::cout << previousword << std::endl;
return 0;
}
Also note that using using namespace std; is discouraged.
You don't need any loops. Just add error checking:
int main() {
std::string text{ "some line with text" };
std::size_t pos2 = text.rfind(' ');
std::size_t pos1 = text.rfind(' ', pos2-1);
std::cout << text.substr(pos1+1, pos2-pos1-1) << std::endl;
return 0;
}
Just keep counting spaces until you arrive to the word you want or use a stringstream as MikeCAT proposed.
Here there is a function that finds any last word number without having to copy the entire string in a stringstream:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
string getNLastWord(string text, int n)
{
bool insideAWord = false;
int wordNum = 0;
int wordEnd = -1;
for(int i = text.size() - 1; i > 0; i--)
{
if(text[i] != ' ' && !insideAWord)
{
wordNum++;
insideAWord = true;
}
else if(text[i] == ' ')
{
insideAWord = false;
}
if(wordNum == n)
{
wordEnd = i;
break;
}
}
if(wordEnd == -1)
{
cout << "There are no " << n << " words from right." << endl;
}
else
{
int wordStart;
for(wordStart = wordEnd; wordStart > 0; wordStart--)
{
if(text[wordStart] == ' ')
{
wordStart++;
break;
}
}
return text.substr(wordStart,wordEnd+1-wordStart);
}
return "";
}
int main() {
string text = "some text";
cout << getNLastWord(text,2);
return 0;
}

C++ Input to only accept operator symbols or only numbers

I've been trying to code this as sort of a beginner program for C++ to help me understand the language more but I don't really know how to tackle this.
Basically the program needs to only accept '+', '*', '/', '%' or numbers, otherwise it will say the input is invalid.
Here's what I've done so far
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout<<"Enter expression: ";
getline(cin,x);
if(x.find('*') != string::npos){
cout<<"Multiplication";
}else if(x.find('/') != string::npos){
cout<<"Division";
}else if(x.find('%') != string::npos){
cout<<"Modulo";
}else if(x.find('+') != string::npos){
cout<<"Addition";
}else{
cout<<"Invalid!";
}
return 0;
}
Definition of the Valid Input
Here I assume that the valid input is given by the following natural statements. First of all, as you mentioned,
Each input must be constructed from *, /, %, + and an integer.
Only zero or one operation. ( So 1+1 is valid. )
For an input of an integer, I also assume
Whitespace characters are allowed in the left and right side of the input string.
Whitespace characters between non-whitespace characters are not allowed.
The first non-whitespace character must be 0, 1, ..., 9 or - (for negative integers).
The second and the subsequent non-whitespace characters must be 0, 1, ..., 8 or 9.
Note that in my assumption the positive sign character +, decimal-point character . are not allowed for integer inputs.
For instance, in this definition,
"123", " 123", "123 " and " -123 " are all valid integer inputs.
"abc", "123a", " 1 23", "+123" and "1.0" are all invalid ones.
Validity Check Function for An Integer
First, to check the validity of the input of an integer, we trim the input and remove left and right whitespaces using the following trimming function: ( If you can use C++17, std::string_view would be more preferable from the performance poin of view.)
#include <string>
std::string trimLR(const std::string& str)
{
const auto strBegin = str.find_first_not_of(" \f\n\r\t\v");
if (strBegin == std::string::npos){
return "";
}
const auto strEnd = str.find_last_not_of(" \f\n\r\t\v");
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
Next, we define the following simple validity check function isInteger which checks whether the passed string is an integer or not. Here std::isdigit is useful to check whether each character is digits or not.
Please note that various interesting methods are proposed in the past
posts.
#include <string>
#include <algorithm>
bool isInteger(const std::string& s)
{
const auto ts = trimLR(s);
if(ts.empty()){
return false;
}
const std::size_t offset = (ts[0] == '-') ? 1 : 0;
const auto begin = ts.cbegin() + offset;
return (begin != ts.cend()) // false if s is just a negative sign "-"
&& std::all_of(begin, ts.cend(), [](unsigned char c){
return std::isdigit(c);
});
}
Main Function
Now it is easy and straightforward to implement the main function.
The following code will check inputs and work fine.
The next considerations are writing tests and performance tunings:
DEMO(Multiplication)
DEMO(Division)
DEMO(Modulo)
DEMO(Addition)
DEMO(Invalid 1)
DEMO(Invalid 2)
#include <iostream>
int main()
{
std::string x;
std::cout << "Enter expression: ";
std::getline(std::cin, x);
const auto optPos = x.find_first_of("*/%+");
if (optPos == std::string::npos)
{
if(isInteger(x)){
std::cout << "Valid input, " << x;
}
else{
std::cout << "Invalid input, " << x;
}
return 0;
}
const auto left = x.substr(0, optPos);
const auto opt = x.substr(optPos, 1);
const auto right = x.substr(std::min(optPos+1, x.length()-1));
if (!isInteger(left) || !isInteger(right))
{
std::cout
<< "Either `" << left << "`, `" << right
<< "` or both are invalid inputs." << std::endl;
return 0;
}
const auto leftVal = std::stod(left);
const auto rightVal = std::stod(right);
if(opt == "*")
{
std::cout
<< "Multiplication: "
<< x << " = " << (leftVal * rightVal);
}
else if(opt == "/")
{
std::cout
<< "Division: "
<< x << " = " << (leftVal / rightVal);
}
else if(opt == "%")
{
std::cout
<< "Modulo: "
<< x << " = " << (std::stoi(left) % std::stoi(right));
}
else if(opt == "+")
{
std::cout
<< "Addition: "
<< x << " = " << (leftVal + rightVal);
}
return 0;
}

How can we found several words in C++ in a text file?

In my project, I need to sort out a list in a file.txt file contains different words. I need my program to recognize this 3 names : bob, alicia and cookie. And each time when he found for exemple "cookie" I want to display "dog" as a result, for "alicia" "girl" and for "bob" "boy" and for an other word "unknown".
The text file contains :
hello
shirley
cookie
bob
alicia
cook
road
alicia
stole
bob
So I did this type of code :
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream input;
size_t pos;
string line;
input.open("file.txt");
if(input.is_open())
{
while(getline(input,line))
{
pos = line.find("cookie");
pos = line.find("bob");
pos = line.find("alicia");
if(pos!=string::npos) // string::npos is returned if string is not found
{
cout <<"dog \n";
cout <<"girl \n";
cout <<"boy \n";
break;
}
}
}
}
And when this code take file.txt like an entry I didn't have the right result like this :
unknown
unknown
dog
boy
girl
unknown
unknown
girl
unknown
boy
Can you help me please because I don't know can I have this result?
Few problems here
You are rewriting the pos in the while loop.
You only print dog girl and boy at once if you find alicia in the file(pos overwriting issue).
You are not handling the case for unknown.
Hence replace your
while(getline(input,line))
{
pos = line.find("cookie");
pos = line.find("bob");
pos = line.find("alicia");
if(pos!=string::npos) // string::npos is returned if string is not found
{
cout <<"dog \n";
cout <<"girl \n";
cout <<"boy \n";
break;
}
}
with
while(getline(input,line))
{
if ((line.find("bob")) != string::npos)
{
cout <<"boy \n";
}
else if ((line.find("alicia")) != string::npos)
{
cout <<"girl \n";
}
else if ((line.find("cookie")) != string::npos)
{
cout <<"dog\n";
}
else
{
cout <<"unknown \n";
}
}
Output:
unknown
unknown
dog
boy
girl
unknown
unknown
girl
unknown
boy
Note :: This approach finds the one word(including substring) in each line.
Using the stream extracion operator >> would have been easier:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
int main()
{
char const *filename{ "file.txt" };
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading!\n\n";
return EXIT_FAILURE;
}
std::string word;
while (is >> word) {
if (word == "cookie")
std::cout << "dog\n";
else if (word == "bob")
std::cout << "boy\n";
else if (word == "alicia")
std::cout << "girl\n";
else
std::cout << "unknown\n";
}
}
If it would be required that only the first word of a line be considered a name one could write a manipulator that eats everything until a newline or EOF is encountered:
std::istream& eat_till_newline(std::istream& is)
{
int ch;
while ((ch = is.get()) != EOF && ch != '\n');
return is;
}
usage:
while (is >> word >> eat_till_newline)
To further narrow down what a word is, one could remove all non-letters from the right of the string:
#include <string>
#include <cctype>
// ...
std::string r_trim(std::string str, int(*pred)(int))
{
std::size_t i = str.length();
if (!i)
return str;
for(; i > 0 && !pred(static_cast<int>(str[i-1])); --i);
return str.substr(0, i);
}
usage:
while (is >> word >> eat_till_newline) {
word = trim_r(word, std::isalpha);
if (word == "cookie")
std::cout << "dog\n";
else if (word == "bob")
std::cout << "boy\n";
else if (word == "alicia")
std::cout << "girl\n";
else
std::cout << "unknown\n";
}
To put it all together:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
std::istream& eat_till_newline(std::istream& is)
{
int ch;
while ((ch = is.get()) != EOF && ch != '\n');
return is;
}
std::string r_trim(std::string str, int(*pred)(int))
{
std::size_t i = str.length();
if (!i)
return str;
for(; i > 0 && !std::isalpha(static_cast<int>(str[i-1])); --i);
return str.substr(0, i);
}
int main()
{
char const *filename{ "test.txt" };
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading!\n\n";
return EXIT_FAILURE;
}
std::string word;
while (is >> word >> eat_till_newline) {
word = r_trim(word, std::isalpha);
if (word == "cookie")
std::cout << "dog\n";
else if (word == "bob")
std::cout << "boy\n";
else if (word == "alicia")
std::cout << "girl\n";
else
std::cout << "unknown\n";
}
}

C++ remove punctuation marks and spaces from a string

How can I remove punctuation marks and spaces from a string in a simple way without using any library functions?
int main()
{
string s = "abc de.fghi..jkl,m no";
for (int i = 0; i < s.size(); i++)
{
if (s[i] == ' ' || s[i] == '.' || s[i] == ',')
{
s.erase(i, 1); // remove ith char from string
i--; // reduce i with one so you don't miss any char
}
}
cout << s << endl;
}
Assuming you can use library I/O like <iostream> and types like std::string and you just don't want to use the <cctype> functions like ispunct().
#include <iostream>
#include <string>
int main()
{
const std::string myString = "This. is a string with ,.] stuff in, it.";
const std::string puncts = " [];',./{}:\"?><`~!-_";
std::string output;
for (const auto& ch : myString)
{
bool found = false;
for (const auto& p : puncts)
{
if (ch == p)
{
found = true;
break;
}
}
if (!found)
output += ch;
}
std::cout << output << '\n';
return 0;
}
No idea about the performance, I'm sure it can be done in multiple better ways.