number of occurences and trim methods... I need help ..

N

nightrosee

hello every body

how are you? I hope you are all having a nice day..
I have to write two methods, the first one counts the number of
occurrences of a character ch in a string ( Numoccurs(char ch) )
and the second removes leading and trailing characters from a string (
Trim(string &str) )..

pleeeeeeeeeeeeeeeeeeeeeeeeeeeeeese help me
 
I

Ivan Vecerina

: hello every body
:
: how are you? I hope you are all having a nice day..
: I have to write two methods, the first one counts the number of
: occurrences of a character ch in a string ( Numoccurs(char ch) )
: and the second removes leading and trailing characters from a string (
: Trim(string &str) )..

To write the first method, an experienced programmer would use
std::count in <algorithm>. For the second, std::string has
find_first/last_not_of methods.
But neither of these approaches is likely to be allowed for homework.
If this is the case, I suggest you read:
http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.2
First give it a try by yourself.

Ivan
 
N

nightrosee

thanks Ivan
but I wrote the first method as following and it didn't give me any
value
int string::Numoccurs(char ch)
{

// char *tmpstr= new char[this->length];
// sptr = tmpstr;

int count = 0;
if ( *sptr!=0)
{
for ( int i =0; i <= this->length;i++){
if (ch== sptr)
count++;
}
}

return count;
}

!!!
 
P

Phlip

nightrosee said:
but I wrote the first method as following and it didn't give me any
value
int string::Numoccurs(char ch)

What do you think the string:: is supposed to do? You can't add a new method
to string like that.

Try int NumOccurs(string str, char c).

In future, write much less code before testing it. You should start with
only this:

int NumOccurs(string str, char c)
{
return -1;
}

Now test it and see it return 0 before continuing:

#include <assert.h>

int main()
{
assert(-1 == NumOccurs("ain't", 'Z');
return 0;
}

After that works, get this to work:

assert(0 == NumOccurs("ain't", 'a');

Tiny little steps like that is how all programmers should write the biggest
programs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top