Latest

recent

Strlen() function in C++


The most popular library is almost certainly the string library, with perhaps the function strlen() called most often. strlen() returns the length of a null-terminated string. Listing 21.1 illustrates its use.

Listing 21.1. strlen().

1: #include <iostream.h>
2: #include <string.h>
3:
4: int main()
5: {
6: char buffer80];
7: do
8: {
9: cout << "Enter a string up to 80 characters: ";
10: cin.getline(buffer,80);
11: cout << "Your string is " << strlen(buffer);
12: cout << " characters long." << endl;
13: } while (strlen(buffer));
14: cout << "\nDone." << endl;
15: return 0;
16: }


Output: Enter a string up to 80 characters: This sentence has 31 characters
Your string is 31 characters long.
Enter a string up to 80 characters: This sentence no verb
Your string is 21 characters long.
Enter a string up to 80 characters:
Your string is 0 characters long.

Done.

Analysis: On line 6, a character buffer is created, and on line 9 the user is prompted to enter a string. As long as the user enters a string, the length of the string is reported on line 11.

Note the test in the do...while() statement: while (strlen(buffer)). Since strlen() will return 0 when the buffer is empty, and since 0 evaluates FALSE, this while loop will continue as long as there are any characters in the buffer.

Goto String Standard Library to get all the String functions
Strlen() function in C++ Reviewed by 1000sourcecodes on 21:39 Rating: 5
Powered by Blogger.