Counting characters in string (C++)

Started by
9 comments, last by deadimp 17 years, 11 months ago
How do I count the charachters in a string in C++?
Advertisement
That depends a lot on what you have access to...

if you are using libraries with a string class then they all have a length function.

if you want to do it by hand.

int strlend(char * string)
{
int x = 0;
while (string[x] != '\0')
{
x++
}

return x;
}
wouldn't hurt to check for a null string and support UNICODE while your at it:)

Cheers
Chris
CheersChris
In C++, use the size or length method:

#include <iostream>#include <string>using namespace std;int main(){    string s1("GameDev.net");    cout << s1.length() << '\n';    cout << s2.size() << '\n';}
"We confess our little faults to persuade people that we have no large ones." -Francois de La Rochefoucauld (1613 - 1680). | My blog
Quote:Original post by TheTroll
That depends a lot on what you have access to...

if you are using libraries with a string class then they all have a length function.

if you want to do it by hand.

int strlend(char * string)
{
int x = 0;
while (string[x] != '\0')
{
x++
}

return x;
}


If i want to use the built in function, what do I write? I tried
count = lenght(name);
but it didn't work. I'm including the iostream library and string library.
it would be...

string i;

count = i.length();

theTroll
OK is this C or C++, because right now you're using C style strings(char*'s). If you want to use C strings, then the function you want is strlen. If you're using C++ then create an actual string object like in rohde's example.
Quote:Original post by rohde
cout << s2.size() << '\n';


that worked, thank you
Quote:Original post by rohde
In C++, use the size or length method:

#include <iostream>#include <string>using namespace std;int main(){    string s1("GameDev.net");    cout << s1.length() << '\n';    cout << s2.size() << '\n';}


Umm... Why '\n' instead of endl which is the same length and easier to type.

"Those who would give up essential liberty to purchase a little temporary safety deserve neither liberty nor safety." --Benjamin Franklin

Quote:Original post by Mike2343
Quote:Original post by rohde
In C++, use the size or length method:

#include <iostream>#include <string>using namespace std;int main(){    string s1("GameDev.net");    cout << s1.length() << '\n';    cout << s2.size() << '\n';}


Umm... Why '\n' instead of endl which is the same length and easier to type.


No reason other than habbit [smile] You might as well use endl - and it would probably be better style.
"We confess our little faults to persuade people that we have no large ones." -Francois de La Rochefoucauld (1613 - 1680). | My blog

This topic is closed to new replies.

Advertisement