Computer Science Canada

Length of a String

Author:  Flikerator [ Thu Jun 08, 2006 12:06 pm ]
Post subject:  Length of a String

I was writing a program yesterday near the end of class (business not programming) and I needed to know what the length of the string was. So I went looking at strings (Untill then I had done nothing with strings/chars). I found only "C-Strings" which is;

#index <string>

Apparently thats not a part of C++? I had to look through some C stuff (Which is very similar to C++ I find). I found strlen() but all my attempts to use it ended up in errors. So today I decided to make my own instead of trying to get C-Strings to work.

code:

#include <iostream>

int Length (char line [255]);

int main()
{
   char Line[] = "hello";
   std::cout << "The length of '" << Line << "' as a string is " << Length (Line);
   std::cin.ignore();
}

int Length (char line [])
{
    int n = 0;
    for (int i=0; i<10; i++)
    {
        std::cout << line [i] << "   " << n << std::endl;
        if (line[i] == ('\0'))
        {
            return (n);       
        }
        n++;
    }
}


A few questions. How could I make my own library (or something like that) so I could call it at the beggining of my program instead of including the function in every Program I need it in?

Is there any problems with this, or things that could be altered to make it faster or more reliable?

How does the C-String for length work? I don't need it know, but why not learn it anyways right? Nothing wrong with learning alternative methods, especially if I have a library and Im programming somewhere without it.

Oh and just a general question, why include (or not include) return 0; in "int main();"

Thanks for your time!

Author:  wtd [ Thu Jun 08, 2006 12:24 pm ]
Post subject: 

If you're using C++, then use the C++ string class.

http://www.msoe.edu/eecs/ce/courseinfo/stl/string.htm

Author:  Null [ Thu Jun 08, 2006 4:30 pm ]
Post subject: 

Just to exand what you said wtd. Smile

A string in C is simply an array of chars. There is no abstraction, and string operations are difficult.

In C++, the standard string class (std::string) was written to encapsulate lots of useful information such as the string's length, and many useful methods.

code:

#include <iostream>
#include <string>

int main() {
        std::string msg = "Hello, world!";

        std::cout << "The string \"" << msg << "\" has a length of " << msg.length() << std::endl;
}


OUTPUT
The string "Hello, world!" has a length of 13

Author:  Null [ Thu Jun 08, 2006 4:32 pm ]
Post subject: 

Oh, and I apologise for double posting, but for some reason I am not allowed to edit posts.

In standard C++, there is an implicit return 0 at the end of the main function if you do not write it yourself.

Author:  Flikerator [ Mon Jun 12, 2006 11:50 am ]
Post subject: 

Forgot all about this (^^Wink..Thanks for the help. Going to check out the C++ Strings now ^_^


: