how do you find the length of a CString?

Dani AI

Generated

Short answer: use the CString member that returns the string length (it counts characters, not the terminating NUL). pointed to the class method; ’s suggestion of strspn is not correct for this — strspn only measures how many leading characters belong to a given character set, not the overall string length.

CString s = _T("Hello");
int len = s.GetLength();   // 5 (characters, excludes the null terminator)

LPCTSTR p = static_cast<LPCTSTR>(s);
int len2 = _tcslen(p);     // equivalent to GetLength() for TCHAR builds

Notes and common traps:

  • GetLength() returns an int representing characters. It does not return bytes; in Unicode builds each character can be multiple bytes, so use GetLength() * sizeof(TCHAR) when you need raw byte size.
  • Prefer GetLength() over C functions like strlen() unless you are absolutely sure you are in an ANSI (narrow) build. Using strlen() on a wide-character CString will break.
  • If you need to modify the internal buffer, use GetBuffer(n) and then ReleaseBuffer() (or ReleaseBuffer(newLen)) so CString knows the new length and maintains the terminator.
  • For explicit ANSI/Unicode code, use CStringA/CStringW and the corresponding strlen/wcslen if you must call C APIs.

In short: GetLength() is the right, safe, and portable choice for CString length.

Recommended Answers

All 4 Replies

I thought it was strspn(parameters); ?

I thought it was strspn(parameters); ?

Isn't that for SubString Search?

It might be. I was trying to recall from memory, so I wouldn't doubt it if I'm wrong. I'll check it out real fast.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.