How to get the length of a string in C ? (.length() vs .size())
在C 中,std::string的.length()和.size()功能完全相同,均返回字符数量(size_t类型);.length()侧重文本语义,.size()契合STL容器统一接口;二者对空串、含空格及'\0'的字符串均准确计数。

In C , you can get the length of a std::string using either .length() or .size() — they do exactly the same thing and return the number of characters as a size_t.
What’s the difference between .length() and .size()?
There is no practical difference. Both are member functions of std::string, and both return identical values. The choice is mostly stylistic or contextual:
-
.length()emphasizes the idea of “how many characters are in this string” — more natural when thinking about text. -
.size()aligns with the standard container interface (e.g.,std::vector::size(),std::array::size()) — preferred if you're treating strings uniformly with other STL containers.
How to use them safely
Both return size_t, which is an unsigned type. Be careful when mixing with signed integers or doing arithmetic that could underflow:
- Avoid comparing
str.length() - 1 — it will always be false since <code>size_twraps around on underflow. - Cast to a signed type only when necessary, and verify the string isn’t empty first.
- Prefer
!str.empty()overstr.length() > 0for readability and efficiency.
What about C-style strings?
If you’re working with null-terminated C-style strings (char*), neither .length() nor .size() applies. Use std::strlen() instead:
const char* cstr = "hello";<br>size_t len = std::strlen(cstr); // returns 5
Empty and edge cases
Both methods work consistently for all valid std::string states:
-
std::string s;→s.length() == 0ands.size() == 0 -
std::string s = "";→ same result -
std::string s = "a";→ both return1 - They count all characters, including spaces, tabs, and null bytes (
'\0') — unlike C-style string functions.
The above is the detailed content of How to get the length of a string in C ? (.length() vs .size()). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20606
7
13699
4




