Write a program to find the length of a string. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Write a program to find the length of a string.

1st Apr 2017, 5:17 AM
Tehreem
5 Answers
+ 16
#include <iostream> #include <cstring> using namespace std; int main() { string str; cin >> str; cout << "Length of string : " << strlen(str.c_str()); return 0; }
1st Apr 2017, 5:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
Why not just use length() of string class.
1st Apr 2017, 6:07 AM
Karl T.
Karl T. - avatar
+ 5
#include <iostream> #include <sstream> using namespace std; int main () { string word; char letter; int num = 0; cout<<"enter a word: "; cin>>word; stringstream s(word); while(s>>letter) { num++; } cout<<"the length of the string is: "<<num; return 0; }
1st Apr 2017, 5:37 AM
chris
chris - avatar
+ 3
to understand stringstream look at this it has very clear comments too. https://code.sololearn.com/cxbsvjtABY48/?ref=app
1st Apr 2017, 5:40 AM
chris
chris - avatar
+ 2
When you are using string object to handle strings, then calling length() function w.r.t to string object shall be more effective for getting the length of the string #include <iostream> #include <string> using namespace std; int main () { string str="Lengthy String"; cout << "The size of str is " << str.length() << " bytes.\n"; return 0; }
1st Apr 2017, 6:12 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar