C++ length of a string | SoloLearn: Learn to code for FREE!


C++ length of a string

Is there a way I can get the length of c++ string? (Purpose is so I can then copy the characters to another array)

10/29/2018 9:42:54 AM


6 Answers

New Answer


if you are using C++, not C, you should be able to use std::string which has method length().


Perhaps this can help you. https://code.sololearn.com/cd3v14lzvCGa/?ref=app


// Use this function: int lengthOf(string str) { int len = 0; while(str[len]) { // Gets the character at len index. If it is there, then it will return a // character, which is true in boolean, but no character // (aka end of string) will result in undefined, which is false. len++; } return len; }


or if you're using char array char s[]="hello"; cout<<sizeof(s)/sizeof(s[0]); //6, because it end with \0


you can use strlen() to find string length...but to copy the string you don't need to use strlen(),,,you can use strcpy() to copy the string


For null terminated strings that originate in other functions you have strlen()