hi guys! ;)
i'm tryng to make a class string...
i'm wondering how to make a member function that can show the string length w/o using strlen..please help! :?:

i already made a program that prints the length of the string w/o using strlen...but the problem is, it's in the main function...

i'm wondering how to pass by reference a string...is it possible?

please help :cry:

You seem to have two questions on your mind.

1) How do I have a member function length?

class String {

   char* fString;
public:
    // constructors
    String();
    String(const char*);

    int getLength();
    ....
}

int String::getLength() {
   //  put code in here for length...
}

2) How do I pass a string by reference?
In the case where you do have a String class I wouldn't pass a string in at all. Ideally your string class should go like this:

String helloString("Hello Dave");
cout << helloString.length();

But if you must know, this is how you pass a string into a function:

int length(char* string) {
...
}


void main() {

    char string[26] = "Hi....";
    length(string);
}

Sure you can pass a string as a reference! Return one too!

// Like anything else, a string can be passed by reference
    // Generally this allows setting the POINTER to the variable,
    // rather than filling in the variable as strcpy() would.
    // Think of this like passing char** theName
void GetName( char* & theNameByRef, char** theNameByPtr )
{
    theNameByRef = "Chainsaw";  // yes, theName now POINTS TO the literal
    *theNameByPtr = "Chainsaw"; // same effect, but the syntax is different
}

char** TheNamePtr( char* n )
{
    return &n;  // a pointer to a pointer to chars
}
char*& TheName( char* n )
{
    return n; // same effect, but simpler syntax.  This returns a REFERENCE to the char*
}

wow! thanks! :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.