How should I get the number of characters in a string in C++?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
if you're using std::string, there are two common methods for that:
if you're using the C style string (using char * or const char *) then you can use:
In C++ std::string the length() and size() method gives you the number of bytes, and not necessarily the number of characters !. Same with the c-Style sizeof() function!
For most of the printable 7bit-ASCII Characters this is the same value, but for characters that are not 7bit-ASCII it's definitely not. See the following example to give you real results (64bit linux).
There is no simple c/c++ function that can really count the number of characters. By the way, all of this stuff is implementation dependent and may be different on other environments (compiler, win 16/32, linux, embedded, ...)
See following example:
It depends on what string type you're talking about. There are many types of strings:
const char*
- a C-style multibyte stringconst wchar_t*
- a C-style wide stringstd::string
- a "standard" multibyte stringstd::wstring
- a "standard" wide stringFor 3 and 4, you can use
.size()
or.length()
methods.For 1, you can use
strlen()
, but you must ensure that the string variable is not NULL (=== 0)For 2, you can use
wcslen()
, but you must ensure that the string variable is not NULL (=== 0)There are other string types in non-standard C++ libraries, such as MFC's
CString
, ATL'sCComBSTR
, ACE'sACE_CString
, and so on, with methods such as.GetLength()
, and so on. I can't remember the specifics of them all right off the top of my head.The STLSoft libraries have abstracted this all out with what they call string access shims, which can be used to get the string length (and other aspects) from any type. So for all of the above (including the non-standard library ones) using the same function
stlsoft::c_str_len()
. This article describes how it all works, as it's not all entirely obvious or easy.It might be the easiest way to input a string and find its length.
Simplest way to get length of string without bothering about std namespace is as follows
string with/without spaces
string without spaces