Advertisement Jump to content
Sign in to follow this  
Zyndrof

Counting characters in string (C++)

This topic is 4640 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
}

Share this post


Link to post
Share on other sites
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';
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!