36

I have following code that gets and prints a string.

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

int main()
{
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    cout << str;
    getch();
    return 0;
}

But how to count the number of characters in this string using strlen() function?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Akash Sharma
  • 801
  • 1
  • 9
  • 19

7 Answers7

101

For C++ strings, there's no reason to use strlen. Just use string::length:

std::cout << str.length() << std::endl;

You should strongly prefer this to strlen(str.c_str()) for the following reasons:

  1. Clarity: The length() (or size()) member functions unambiguously give back the length of the string. While it's possible to figure out what strlen(str.c_str()) does, it forces the reader to pause for a bit.

  2. Efficiency: length() and size() run in time O(1), while strlen(str.c_str()) will take Θ(n) time to find the end of the string.

  3. Style: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use std::sort over qsort or std::lower_bound over bsearch, unless some other factors come into play that would affect performance.

The only reason I could think of where strlen would be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which strlen differs from string::length; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use string::find:

size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;
starball
  • 20,030
  • 7
  • 43
  • 238
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Your code is correct , but i have read that all functions of c are imported in C++ and we can use strlen in C , how to use in C++ – Akash Sharma Nov 24 '13 at 21:00
  • 4
    @AkashSharma- You *can* use `strlen` on a C++ string by writing `strlen(str.c_str())`, but this would be extremely poor style. Although C++ absorbs C's standard library, the C++ standard libraries often include more C++-friendly versions of those functions, and there's no reason to use `strlen` when you could just be using `string::length`. – templatetypedef Nov 24 '13 at 21:01
  • If i want to use `strlen()` then Why can't I use `strlen(str);` – Akash Sharma Nov 24 '13 at 21:18
  • 4
    @AkashSharma- `strlen` accepts `const char*`, and `std::string` isn't a `const char*`. That said - it is really not a good idea to use `strlen` here! – templatetypedef Nov 24 '13 at 21:19
  • Ok, But another issue why there are two functions `size()` and `length()` as i can see both doing same work? – Akash Sharma Nov 24 '13 at 21:21
  • 3
    @AkashSharma- I believe it's historical. The STL contains use `size()`, and I think historically `string` used `length()`. It's probably for backwards compatibility. – templatetypedef Nov 24 '13 at 21:23
  • @templatetypedef: Correct. There's running C++ code going back 20+ years, and we strive not to break reasonable code. That's also why `strlen` is still valid: we may have better alternatives, but old code doesn't magically change to use those. – MSalters Nov 25 '13 at 10:48
  • There's actually a difference I stumbled across lately: If you do `str[4]` where `str.length() == 100`, then afterwards `strlen(str.c_str()) == 4` whereas still `str.length() == 100`. (Old answer, but better late than never:) – Xlea Mar 27 '15 at 13:19
  • 1
    @Xlea You probably mean `str[4] = '\0'`? – Emil Laine Mar 22 '16 at 10:16
  • 1
    @zenith Right, I do. – Xlea Mar 23 '16 at 19:32
6

Function strlen shows the number of character before \0 and using it for std::string may report wrong length.

strlen(str.c_str()); // It may return wrong length.

In C++, a string can contain \0 within the characters but C-style-zero-terminated strings can not but at the end. If the std::string has a \0 before the last character then strlen reports a length less than the actual length.

Try to use .length() or .size(), I prefer second one since another standard containers have it.

str.size()
masoud
  • 55,379
  • 16
  • 141
  • 208
  • `.size` was correct, too. I actually use it instead of `length`. – Kiril Kirov Nov 24 '13 at 20:57
  • Why two functions size() and length() are given in C++ ? Any specific reason? Because Both are doing same work. – Akash Sharma Nov 24 '13 at 21:09
  • 1
    @AkashSharma You can check it here: [size and length](http://stackoverflow.com/questions/905479/stdstring-length-and-size-member-functions) – jcm Nov 24 '13 at 21:12
2

Use std::string::size or std::string::length (both are the same).

As you insist to use strlen, you can:

int size = strlen( str.c_str() );

note the usage of std::string::c_str, which returns const char*.

BUT strlen counts untill it hit \0 char and std::string can store such chars. In other words, strlen could sometimes lie for the size.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • [`c_str()`documentation from cppreference](http://en.cppreference.com/w/cpp/string/basic_string/c_str): Returns a pointer to a **null-terminated character array** with data equivalent to those stored in the string. – Johan Nov 24 '13 at 21:03
  • @Johan: Not necessarily. A `std::string` can contain embedded null characters. If you have a `std::string` `foo` with the value `"foo\0bar"`, it's `.length()` is 7, but `strlen(foo.c_str())` will return 3. – Keith Thompson Nov 24 '13 at 21:06
  • My mistake, I read your message the other way (that there was no '\0' at the end). – Johan Nov 24 '13 at 21:06
  • Sorry I removed my previous comment that was becaming meaningless. – Johan Nov 24 '13 at 21:07
1

If you really, really want to use strlen(), then

cout << strlen(str.c_str()) << endl;

else the use of .length() is more in keeping with C++.

KeithSmith
  • 774
  • 2
  • 8
  • 26
0

Manually:

int strlen(string s)
{
    int len = 0;

    while (s[len])
        len++;

    return len;
}
user2972135
  • 1,361
  • 2
  • 8
  • 10
0
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()

{
    char str[80];

    int i;

    cout<<"\n enter string:";

    cin.getline(str,80);

    int n=strlen(str);

    cout<<"\n lenght is:"<<n;

    getch();

    return 0;

}

This is the program if you want to use strlen . Hope this helps!

Opal
  • 81,889
  • 28
  • 189
  • 210
-2

Simply use

int len=str.length();

Jakarea Parvez
  • 540
  • 6
  • 9