Counting characters in string (C++)
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 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
Cheers
Chris
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';}
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.
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
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.
Quote:Original post by Mike2343Quote: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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement