Finding the length of strings?

Apr 15, 2014 at 12:42am
Is there any way to determine the length of a string without the use of iterating through the string until you find the null terminator. Because in some code I have, some of the strings im trying to find the length of have '\0' all over the place, not just at the end
Apr 15, 2014 at 12:49am
For std::string, use the .size() member function:
1
2
std::string str = "Hello world!";
std::cout << str.size(); // Prints the size of the string (12) 

For C-style strings (char arrays), you'll have to use a character other than '\0', because that character is used specifically to designate the end of the string.
You could try to use a separate size variable and just keep track of the size yourself, but that doesn't help if you don't know the initial size beforehand.
Apr 15, 2014 at 1:21am
You can also use .length() member function for strings as it is perhaps a bit easier to remember.
Last edited on Apr 15, 2014 at 1:22am
Apr 15, 2014 at 8:02pm
@codegoggles - std:string won't work since the the OP states the data contains embeded nulls.

@OP - Since you say your data has embeded nulls, you're not dealing with conventional strings. Storing your data as a std::string or even a C-string isn't going to help. Since you can't rely on a null terminator, what determines the length of your data? As long double main suggested, you're going to need to keep track of the length yourself.

Maybe something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Data 
{  size_t m_len;
    char * m_data;
public:
    Data ()  // Default constructor
    {  m_data = NULL; m_len = 0; }

    // Construct from an explicit buffer
    Data (char *buf, size_t len)
    { m_data = new char[len]; 
       m_len = len;
       memcpy (m_data, buf, len);
    }

    ~Data ()
    { if (m_data)
         delete m_data;
    }

    char * get_data ()
    { return m_data; }

    size_t get_len ()
    { return m_len; }

};

Apr 15, 2014 at 8:06pm
@AbstractionAnon: Fortunately, std::string fully supports embedded nulls, as the standard dictates.
1
2
std::string str ("Hello\0world", 11);
std::cout << str.length() << std::endl;


Also, I would prefer a begin and end pointer over a pointer and length. At the very least, have length be of type std::ptrdiff_t rather than std::size_t.
Last edited on Apr 15, 2014 at 8:12pm
Apr 15, 2014 at 8:09pm
@AbstractionAnon

OP did not specify container. A std::string is designed specifically to permit embedded nulls, so it would be the perfect solution to his problem.

Assuming he hasn't left out some important information about source/container requirements...
Apr 15, 2014 at 8:20pm
@LB and Duoas. You're right, of course. It slipped my mind that std::string can contain embeded nulls.
Topic archived. No new replies allowed.