I am trying to write a program that strips non-alpha characters from both sides of a string, but leave the non-alpha character(s) inside the string alone.
#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
usingnamespace std;
string nonAlpha(string input)
{
stringstream ss;
for (int x = 0; x < input.size(); x++)
{
if(isalpha(input[x]))
{
ss << input[x];
}
}
if (ss.str().length() > 0)
return ss.str();
elsereturn"Nothing left";
}
int main()
{
string userInput;
int counter = 0;
cout <<"Enter a word" <<endl;
cin >> userInput;
for(int i = 0; userInput[i] != '\0'; i++)
{
userInput[i] = tolower(userInput[i]);
}
for(int i = 0; i < userInput.size(); i++)
{
while(!isalpha(userInput.at(i)))
{
counter--;
}
cout<<userInput.substr(i)<<endl;
return 0;
}
//cout << userInput <<endl;
}
Whenever I type in a word such as 'the,' the string prints out fine. Whenever I enter in a string with a non-alpha character the runtime is really slow, and nothing prints out. My question is, what can I do to help fix my problem? Thanks.
The name of your function confuses users. Instead of nonAlpha it would be better to use something as trimNonAlpha.
Inside the function body you remove all non-alpha cheracters from the original string. That is not you wanted to do.
Also there is no a great sense to use std::stringstream.
All you need is to find the first alpha character and the last alpha character in the string.
1 2 3 4 5 6 7 8 9 10 11
std::string trimNonAlpha( const std::string &s )
{
std::string::size_type pos = 0;
std::string::size_type n = s.size();
while ( pos < n && !std::isalpha( s[pos] ) ) ++pos;
while ( n != pos && !std::isalpha( s[n - 1] ) ) --n;
return ( s.substr( pos, n - pos ) );
}