String length: Difference between revisions

Content added Content deleted
Line 166: Line 166:
{{works with|ISO C++}}
{{works with|ISO C++}}
{{works with|g++|4.0.2}}
{{works with|g++|4.0.2}}
<lang cpp>#include <string> // note: '''not''' <string.h>
<lang cpp>#include <string> // (not <string.h>!)
using std::string;


int main()
int main()
{
{
std::string s = "Hello, world!";
string s = "Hello, world!";
std::string::size_type length = s.length(); // option 1: In Characters/Bytes
string::size_type length = s.length(); // option 1: In Characters/Bytes
std::string::size_type size = s.size(); // option 2: In Characters/Bytes
string::size_type size = s.size(); // option 2: In Characters/Bytes
// In bytes same as above since sizeof(char) == 1
// In bytes same as above since sizeof(char) == 1
std::string::size_type bytes = s.length() * sizeof(std::string::value_type);
string::size_type bytes = s.length() * sizeof(string::value_type);
}</lang>
}</lang>
For wide character strings:
For wide character strings:


<lang cpp>#include <string>
<lang cpp>#include <string>
using std::wstring;
int main()
int main()
{
{
std::wstring s = L"\u304A\u306F\u3088\u3046";
wstring s = L"\u304A\u306F\u3088\u3046";
std::wstring::size_type length = s.length() * sizeof(std::wstring::value_type); // in bytes
wstring::size_type length = s.length() * sizeof(wstring::value_type); // in bytes
}</lang>
}</lang>


Line 193: Line 195:


<lang cpp>#include <string>
<lang cpp>#include <string>
using std::wstring;


int main()
int main()
{
{
std::wstring s = L"\u304A\u306F\u3088\u3046";
wstring s = L"\u304A\u306F\u3088\u3046";
std::wstring::size_type length = s.length();
wstring::size_type length = s.length();
}</lang>
}</lang>