C++ String Length

πŸ“ C++ String Length

C++ mein string ki length (number of characters) nikalne ke liye mainly 2 functions use hote hain:

  • length()

  • size()

πŸ‘‰ Dono same kaam karte hain.


πŸ”Ή 1. Using length()

#include <iostream>
#include <string>
using namespace std;

int main() {
string txt = "Hello C++";
cout << txt.length();
return 0;
}

Output:

9

πŸ”Ή 2. Using size()

string txt = "Programming";
cout << txt.size();

Output:

11

πŸ”Ή 3. Length with Spaces

string s = "Hello World";
cout << s.length();

Output:

11

➑ Space bhi character maana jata hai.


πŸ”Ή 4. Empty String Length

string s = "";
cout << s.length();

Output:

0

πŸ”Ή 5. User Input String Length

string name;
getline(cin, name);
cout << name.length();

πŸ”Ή 6. Loop Using String Length

string s = "C++";

for (int i = 0; i < s.length(); i++) {
cout << s[i] << " ";
}

Output:

C + +

πŸ”Ή 7. Check Empty String

string s = "";

if (s.empty()) {
cout << "String is empty";
}


❌ Common Mistakes

cout << length(s); // ❌ wrong

βœ” Correct:

cout << s.length();

πŸ“Œ Summary

  • length() = size()

  • Spaces count hote hain

  • Empty string ki length 0 hoti hai

  • Looping & validation mein useful

You may also like...