+ 11

How to get number of characters in a string in c++

What is the syntax for getting the value of the number of characters in a string.

10th Jun 2019, 2:18 AM
Spiff Jekey Green
Spiff Jekey Green - avatar
9 Antworten
+ 12
C++ string class has a length function which returns number of characters in a string. For example int main() { string a = "Hello world"; int b = a.length(); cout << b; return 0; } output : 11
10th Jun 2019, 2:37 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 10
string a = "Hello world"; int b = a.length(); b = 11
10th Jun 2019, 9:40 PM
Jaagrav
Jaagrav - avatar
+ 3
#include <string> string s = "Hello"; cout << s.size(); 5
10th Jun 2019, 2:38 AM
Choe
Choe - avatar
+ 3
#include <iostream> using namespace std; int main() { char s[] = "Hello World"; cout <<sizeof(s); return 0; } // out put : 12
10th Jun 2019, 3:03 AM
Anil Kumar
Anil Kumar - avatar
+ 2
It depends whether you are using STL or not. If you are using String STL,i.e., #include <string>, the way to go would be : string str = "sentence"; length = str.length(); cout<<length; // Output - 8 But, if you are not using STL, and declaring string the traditional way, then the method would be : char str[ ] = "sentence"; length = sizeof(str) - 1; cout<<length; // Output - 8 We subtract 1 from sizeof(string) because every string is terminated by a Null character, hence, it uses an extra byte.
11th Jun 2019, 3:25 AM
Kvothe
Kvothe - avatar
+ 2
There are many ways
11th Jun 2019, 5:32 PM
Justin
Justin - avatar
+ 1
you can use length() function for your string
10th Jun 2019, 1:51 PM
Mohamad.M.Nosrati
Mohamad.M.Nosrati - avatar
+ 1
Loop through the string one chat at a time and increment counter. Do NOT trim spaces. 🤔
10th Jun 2019, 1:58 PM
Sanjay Kamath
Sanjay Kamath - avatar
0
// The simplest way (no methods/functions used)! #include <iostream> using namespace std; int main() { std::string str = "Hello!"; int i; for(i = 0; str[i] != '\0'; i++); // notice this semicolon and '\0' is null char which terminates any C++ string! std::cout << "Length=" << i; return 0; } // Works for char str[] = "Hello!" too!
11th Jun 2019, 1:31 PM
777
777 - avatar