1

I have declared a string array String s;

I tried finding the length of the string by giving strlen(s) but it didnt work . How to get the length of the string ?

2
  • 1
    show the declaration, just to be clear Commented Nov 22, 2010 at 10:53
  • String (with a capital S) is not a class specified in the C++ Standard. If you don't say which library you're using, nobody can say for sure what functions it provides to tell you the length. Still, common options are data members such as s.length(), s.size(). You could look at the header you include to get access to the class, and see what functions it does provide. Commented Nov 22, 2010 at 12:32

4 Answers 4

2

The function strlen does not take a string, but an array of chars. Please see this reference for examples. If you are using the type string you will find it's length by using the function length(), like this:

std::string text = "Some text"; 
int length = text.length(); 

For more examples see this other question.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the member function length().

Comments

1
string s;

declares a string named s, not an array of strings, which would be

string array[10];

for instance. To get the length of a string, you call its size() or length() method:

size_t len = s.size();

3 Comments

Don't forget the std namespace.
Of course. The above assumes you added a using std::string; earlier in the file. :)
I don't think it is a safe assunction, the OP uses String that's not even the correct name :)
0

Alot of methods that I have seen take a const char * (which also might be the 'string' that he is refering to) will loop through the variable until they hit a NULL \0 character.

This often is how 'string arrays' are ended and will usually be a good stop to calculate the string length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.