Remove characters from string

I am writing a program that has to analyze a string and then if there's a contracted form (e.g. "don't") I have to transform it in "do not". To do that, reading cplusplus.com Reference, I have written a function that should help me to solve this issue. When I am trying to call the function I get a run-time-error of type "out-of-range memory" I guess I get wrong something with iterators but I am not sure. This is my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
string remove_trunc(string& s)
{
	const string suffix = " not";
	int temp = s.size();
	if (s.at(temp) == 't' && s.at(temp - 1) == '\'' && s.at(temp - 2) == 'n')
	{
		s.erase(s.begin() + (s.size() - 3), s.end() - 1);
		s += suffix;
	}

	return s;
}


While this is the caller function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void remove_punct()
{
	while (true)
	{
		cout << endl;
		cout << "Type what you want and I will let punctuation disappear:";
		string buffer;
		getline(cin, buffer);

		stringstream ss{ buffer };
		for (string s; ss >> s;)
		{
			s = remove_trunc(s);
		}
		for (string s; ss >> s;)
		{
			for (char& c : s)
			{
				if (ispunct(c) && c != '"') c = ' ';
			}
			cout << s << " ";
		}

	}
}


Thanks
Last edited on
> if there's a contracted form (e.g. "don't") I have to transform it in "do not".

Are you also expected to transform won't, I'll, 'twere etc.?
For now I am trying to do something general so that every suffix "-n't" should be translated in " not". Just this for the moment! Without considering any other kind of contracted forms. That's the idea! It is part of an exercise and this was the request :)
Last edited on
Solved!
 
if (s.at(temp - 1) == 't' && s.at(temp - 2) == '\'' && s.at(temp - 3) == 'n')


instead of
 
if (s.at(temp) == 't' && s.at(temp - 1) == '\'' && s.at(temp - 2) == 'n')


Because of
 
basic_string::at: __n (which is 5) >= this->size() (which is 5)
Something along these lines, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

bool has_suffix( std::string str, std::string suffix )
{
    return str.size() > suffix.size() &&
           str.rfind( suffix ) == ( str.size() - suffix.size() ) ;
}

std::string expand_not( std::string str )
{
    if( has_suffix( str, "'t" ) )
    {
        // special cases:
        if( str == "won't" ) return "will not" ;
        else if( str == "shan't" ) return "shall not" ;
        // else if ...

        // else the general case
        if( has_suffix( str, "n't" ) ) return str.substr( 0, str.size() - 3 ) + ' ' + "not" ;
    }

    return str ;
}

int main()
{
    for( std::string str : { "wouldn't", "won't", "shan't", "didn't", "hello", "don't" } )
         std::cout << str << "  =>  " << expand_not(str) << '\n' ;
}

http://coliru.stacked-crooked.com/a/c14ae5603d441f64
Topic archived. No new replies allowed.