String array length

Is there a way that I can determine the length of a string array? I ask because I want to have a function perform operations on each letter in a name. I cannot properly craft a loop without knowing exactly how long the string array is.
It could be 2-10 characters, how can I know for certain.
1
2
3
4
5
6
7
8
9
string cppStr = "Hello, world!";
cout << s.length() << endl;
cout << s.size() << endl;

char *cStr = "Hello, world!";
cout << strlen(cStr) << endl;
int strLen;
for( strLen = 0; cStr[i] != '\0'; i++ );
cout << strLen << endl;
13
13
13
13
Last edited on
My method has been the for loop until you find the '\0' character.

The problem with that is any one could just add a \0 in there string and then what ever is between that and your final '\0' character will not be counted.
I got a lot of errors from that code. I am assuming that you are using some header files that
I am not aware of. I am also unfamiliar with the strLen function. thanks anyway though.
For that code to compile:

1
2
3
#include <iostream>
#include <string>
using namespace std;


strlen returns the length of a char*. i.e. how many characters there are until the first '\0' (which is the same as what trollger's function does).
Last edited on
I thought strlen was in <cstring> instead.

Anyway, there is a type called BSTR and is the standard string type for COM. Since MS invented COM, I will dare say BSTR was also their invention.

BSTR is a unicode char array that is null terminated, but it stores its size (in bytes) in the 4 bytes preceeding the pointer. This means that you can store null chars in BSTR's.
I thought strlen was in <cstring> instead.

Maybe my compiler is nice to me so when I include <string> it includes <cstring> as well.

Anyway, to be correct across all compilers you should do this, smkelsey:

1
2
3
4
#include <iostream>
#include <cstring>
#include <string>
using namespace std;


Thanks webJose for pointing that out.
Yes, just checked. See http://www.cplusplus.com/reference/clibrary/cstring/. The strlen() function is listed there.
thanks a bunch.
Topic archived. No new replies allowed.