+ 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.
9 Answers
+ 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
+ 10
string a = "Hello world";
int b = a.length();
b = 11
+ 3
#include <string>
string s = "Hello";
cout << s.size();
5
+ 3
#include <iostream>
using namespace std;
int main() {
char s[] = "Hello World";
cout <<sizeof(s);
return 0;
}
// out put : 12
+ 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.
+ 2
There are many ways
+ 1
you can use length() function for your string
+ 1
Loop through the string one chat at a time and increment counter. Do NOT trim spaces. đ€
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!