4

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?

1
  • 1
    You can use the std::string array access operator [] to manipulate single characters in the string. Commented Aug 31, 2013 at 9:09

4 Answers 4

8

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] = ' ';
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Karimkhan define "does not work" ? These !"#$%&'()*+,-./:;<=>?@[\]^_{|}~` are punctuation based on default locale that will be replaced with a space.
@POW: sorry, When I passed above strin in command line it treated as single word! But there was mistake at myside!
6
#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;
}

Comments

5

You could use std::replace_if:

bool fun(const char& c)
{
  return std::ispunct(static_cast<int>(c));
}

int main()
{
  std::string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
  std::replace_if(line.begin(), line.end(), fun, ' ');
}

2 Comments

Do you need the wrapper function? Can't you just pass std::ispunct directly?
@KerrekSB It would be a bit fiddly because std::ispunct expects an int. I opted for the wrapped function for clarity (actually, I got lazy). Of course, a lambda would have been fine too.
3

I hope this helps you

#include <iostream>
#include<string>
using namespace std;
int main()
{
    string line = "ts='TOK_STORE_ID'; one,one, two;four$three two";
    for (int i = 0;i<line.length();i++)
    {
        if (ispunct(line[i]))
        {
            line[i] = ' ';
        }
    }
    cout << line << std::endl;
    cin.ignore();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.