How do I find the null character (\0) in an array string

How do I find the null character (\0) in an array string that a user types in? I need this information to make a function that shows the number of characters in the array string. Thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
char *msg = "test";

int stringLength(char *msg)
{
   int count = 0;
   char *p = msg;
   while (*p != '\0')
   {
      ++p;
      ++count;
   }
return count;
}
Last edited on
I guess, you mean a plain c-string. Since you don't know the size of such string, The only option is, traversing to the whole string and test if a '\0' comes. The standard library has a function which does this job:

http://www.cplusplus.com/reference/cstring/strlen/?kw=strlen

That's basically
1
2
3
4
5
6
int strlen( char * str)
{
    int len = 0;
    while( *str++ ) ++len;
    return len;
}


1) \0 == 0 saves some typing and visual clutter.
2) string.size tells you the end of a c++ string. you should try to use string if in c++, apart from classroom exercises using C code.
3) strlen(foo) tells you the length of a C string, unless the assignment is to DIY, use the tool.

if you need to recreate strlen, then you can use something like the above.
I think it boils down to just this (added error check, removed redundant copy)
1
2
3
4
5
6
7
int strlen2(char* c)
{
   if(!c) return 0; //do you want to make sure its not null coming in?
   int ct = 0; //need a counter at 0 to start
   while(*c) {ct++; c++;} //c isnt reference, so incrementing c is fine, don't need copy. 
   return ct;
}
Last edited on
Thank you, everyone! Especially @nuderobmonkey!
Topic archived. No new replies allowed.