3 Replies - 2110 Views - Last Post: 30 November 2009 - 11:26 AM Rate Topic: -----

#1 joedwalker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-October 09

Remove punctuation from the front of a string

Posted 30 November 2009 - 10:29 AM

I'm trying to remove all punctuation from the front of a string but the function gets rid of the entire word.

I'm using the 'cout' to see what's coming and going out.

if I use .,?bob the entire string gets deleted. Please help.



void RemoveFrontPunct(string &word)
{
cout << "\n\n\n =========== into front: " << word;
for (int i=0; i < word.length(); ++i)
if (ispunct(word[i]))
word.erase(i);
else
break;
cout << "\n\n =========== out from front: " << word;
}

Is This A Good Question/Topic? 0
  • +

Replies To: Remove punctuation from the front of a string

#2 KYA  Icon User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,232
  • Joined: 14-September 07

Re: Remove punctuation from the front of a string

Posted 30 November 2009 - 11:13 AM

Why not use the C++ version?

locale loc;
  string name = "Knowle.s";
  for(string::iterator it = name.begin(); it != name.end(); ++it){
	  if (ispunct(*it, loc)){
		  name.erase(it);
	  }
  }
  cout << name << endl;


Was This Post Helpful? 0
  • +
  • -

#3 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 944
  • View blog
  • Posts: 2,464
  • Joined: 20-August 07

Re: Remove punctuation from the front of a string

Posted 30 November 2009 - 11:16 AM

You can use substr to trim all those punctuation characters at the same time if you know where the first non-punctuation character in your string is.
    size_t i;
    for(i=0; i!=word.length(); ++i)
        if ( !ispunct(word[i]) )
            break;
            
    word = word.substr(i); 

Was This Post Helpful? 0
  • +
  • -

#4 KYA  Icon User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,232
  • Joined: 14-September 07

Re: Remove punctuation from the front of a string

Posted 30 November 2009 - 11:26 AM

Doing what Bench is above the C++ way:

string name = "....??Knowles";
  for(string::iterator it = name.begin(); it != name.end(); it++){
	  if (isalpha(*it)){
		  name.erase(name.begin(), it);
				  break;
	  }
  }
  cout << name << endl;
  return 0;


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1