Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace specific characters in std::string with spaces

Following code removed punctuation marks correctly from char array:

#include <cctype>
#include <iostream>

int main()
{
    char line[] = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (char* c = line; *c; c++)
    {
        if (std::ispunct(*c))
        {
            *c = ' ';
        }
    }
    std::cout << line << std::endl;
}

How would this code look if the line is of type std::string?

like image 949
user123 Avatar asked Nov 30 '22 03:11

user123


2 Answers

It'd look like following, if you simply prefer to use a STL algorithm

#include<algorithm>

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";

std::replace_if(line.begin() , line.end() ,  
            [] (const char& c) { return std::ispunct(c) ;},' ');

Or if you don't want to use STL

Simply use:

std::string line ="ts='TOK_STORE_ID'; one,one, two;four$three two";
std::size_t l=line.size();
for (std::size_t i=0; i<l; i++)
{
    if (std::ispunct(line[i]))
    {
        line[i] = ' ';
    }
}
like image 179
P0W Avatar answered Dec 05 '22 05:12

P0W


#include <iostream>
#include<string>
#include<locale>

int main()
{
    std::locale loc;
    std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";

    for (std::string::iterator it = line.begin(); it!=line.end(); ++it)
            if ( std::ispunct(*it,loc) ) *it=' ';

    std::cout << line << std::endl;
}
like image 34
cpp Avatar answered Dec 05 '22 05:12

cpp