Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a std::string in C++?

Tags:

c++

I'm trying to remove all punctuation characters from a std::string in C++. My current code:

string str_in;
string::size_type i, j;

cout << "please input string with punctuation character..." << endl;
cin >> str_in;

for (i = 0, j = 0; i != str_in.size(); ++i)
    if (!ispunct(str_in[i]))
         str_in[j++] = str_in[i];

str_in[j] = '\0';

cout << str_in << endl;

Is str_in[j] = '\0'; wrong?

like image 284
iverson Avatar asked Dec 20 '25 05:12

iverson


1 Answers

If you want to truncate str_in to the first j characters, you can say str_in.resize(j).

If you want to use the standard library you could apply the erase-remove idiom like this:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string str_in;
    std::getline(std::cin, str_in);

    // Here is where the magic happens...
    str_in.erase(std::remove_if(str_in.begin(), str_in.end(), ::ispunct), str_in.end());

    std::cout << str_in << '\n';

    return 0;
}
like image 184
Blastfurnace Avatar answered Dec 21 '25 20:12

Blastfurnace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!