length function

This is sort of a continuation of this topic
http://www.cplusplus.com/forum/beginner/11887/
Does .length() return a value that acounts for the first element being labeled 0? For example, if your string was called 'hi' and it stored the value "Hello World" would hi.length() return 10 or 11?


EDIT: "Hello World", the line break concealed the space that was there.
Last edited on
why not try it?

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
  string hi = "Hello World";
  cout << hi.length();

  return 0;
}
I don't know why i didn't think of that, thanks. It returns 11.
Last edited on
It will return the entire length of the string (whitespace included), sans the null-terminator ('\0').

Hope that helps.
sans the null-terminator ('\0').

Not sure what that means but i hope it means that it doesn't count the null terminator because it is non-existent in string objects.
sans is french for "without".
Check out this:
----------------------------------------------------------------------------------------------------
#include<iostream.h>
#include<conio.h>

int strlength(char hi[]); //Function to find length of string
main()
{
char hi[]="Hello World";
cout<<"Length of string is:\n"<<strlength(hi); //Call to function "strlength"
getch();
}
int strlength(char hi[])
{
int length=0;

for(int i=0;hi[i]!='\0';i++) //loop until encounter null charcter
//Note:length not incremented for "/0"
length++;

return length;
}

--------------------------------------------------------------------------------------------------------------------
AR Khan: Congratulations for reinventing the wheel less than ideally.
@AR Khan: why not return i?
Yes it will work with
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream.h>
#include<conio.h>

int strlength(char hi[]);
main()
{
      char hi[]="Hello World";
      cout<<"Length of string is:\n"<<strlength(hi);
      getch();
}
int strlength(char hi[])
{
    int i;
    
    for(i=0;hi[i]!='\0';i++);
        
    return i;
}


Note: "i" should be declared before for loop.
And thanks for incrementing my knowledge.

Topic archived. No new replies allowed.