+ 4

How to write a C++ program that computes the length of a string entered by the user?

https://code.sololearn.com/cFvcjiyGgILo/?ref=app

1st Mar 2019, 9:46 AM
Janna Al-Ward
Janna Al-Ward - avatar
3 Respostas
+ 8
/*Different methods to find length  of a string in C++*/ #include<string.h>  #include<iostream> using namespace std; int main() {     // String obj      string str ="Computer";      // 1. size of string object using size() method     cout << str.size() << endl;             // 2. size of string object using length method     cout << str.length() << endl;             // 3. size using old style     // size of string object using strlen function      cout << strlen(str.c_str()) << endl;        // The constructor of string will set it to the C-style string,      // which ends at the '\0'            // 4. size of string object Using while loop     int i = 0;     while (str[i] != '\0')     {         ++i;     }     cout << i << endl;        // 5. size of string object using for loop     for (i=0; str[i]!='\0'; i++)     {     }     cout << i << endl;    return 0; } OUTPUTS :- 8 8 8 8 8
1st Mar 2019, 9:54 AM
Ashutosh Sharma
Ashutosh Sharma - avatar
+ 3
You can simply use String.length() method https://code.sololearn.com/cjAVbp0xrmTm/?ref=app
1st Mar 2019, 9:53 AM
Parsa Gholipout
Parsa Gholipout - avatar
+ 2
Thank you so much, Parsa Gholipout and Ashutosh Sharma .
1st Mar 2019, 9:58 AM
Janna Al-Ward
Janna Al-Ward - avatar