Hey I'm working on a function that will take a string as an input from an array. This function will go through the word letter by letter ( I suppose) and if the character at that position is something other then a letter like maybe !! or ?? or even ..... I will remove this part and return the word with the crap taken out. I'm messing around trying to write this function now. It's proving difficult. I wrote a comment where my brain passed gas.
Thanks for any ideas.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string testIt( string str1)
{
string newStr1 (str1.size(), ' ' );
for(int i = 0; i <= str1.size(); i++)
{
if(isalpha(str1[i]))
newStr1[i]= str1[i];
else
str1[i] ////// Stuck How can I erase just one character?
}
}
I did I got a error message that is saying out of range. xthrow.cpp or something.
I don't know why it would be out of range? I read that if it is erase has just exceeded the last position but why this is on this code no idea.
Thanks
The strange thing is that it worked once and I didn;t really change anything now nothing. I don't think this is a bad function I just can find what is wrong. It takes me to that side screen sort of this and says out of range x throw???
In the future, you can look up functions like erase() on this site's reference section, giving you pages like this: http://www.cplusplus.com/reference/string/string/erase/
It can help you figure out what parameters you need to pass and what the function does.
You need not to erase a character because you are coping one string into another except non-alpha characters. So in any case the target string will not contain non-alpha characters.
Your task can be done by using standard algorithm std::copy_if. For example
Your code is invalid because you are returning a string with trailing spaces. I think it is not what you want to have. The result string has to have only alpha characters from the original string without any trailing spaces. So I would rewrite your code the following way
1 2 3 4 5 6 7 8 9 10 11 12 13
string testIt( const string &s )
{
string t;
t.reserve( s.size() );
for ( string::size_type i = 0; i < s.size(); i++ )
{
if ( isalpha( s[i] ) ) t.push_back( s[i] );
}
return t;
}
AHH! OK I see what you are saying the spaces are still there. But you have to explain this part of your code to me. if ( isalpha( s[i] ) ) t.push_back( s[i] );
What exactly is push back I'm unfamiliar with this.
Thanks man
Push and Pop are good words to learn. To push is to add and pop is to access (often remove as well). A "push_back()" would add to the end, pop_front(), would access the beginning.