본문 바로가기

old_Coding/C/C++

[Scrap] length of characters (I/O Function) (*)



strlen, strlen_l, wcslen, wcslen_l, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l



 prototype
size_t strlen( const char *str );
size_t strlen_l( const char *str, _locale_t locale );

size_t wcslen( const wchar_t *str );
size_t wcslen_l( const wchar_t *str, _locale_t locale );

size_t _mbslen( const unsigned char *str );
size_t _mbslen_l( const unsigned char *str, _locale_t locale );

 size_t _mbstrlen( const char *str );
 size_t _mbstrlen_l( const char *str, _locale_t locale );




Each of these functions returns the number of characters in str, excluding the terminal NULL. No return value is reserved to indicate an error, except for _mbstrlen, which returns -1 if the string contains an invalid multibyte character.



 Example from MSDN
// crt_strlen.c
// Determine the length of a string. For the multi-byte character
// example to work correctly, the Japanese language support for
// non-Unicode programs must be enabled by the operating system.

#include <string.h>
#include <locale.h>

int main()
{
   char* str1 = "Count.";
   wchar_t* wstr1 = L"Count.";
   char * mbstr1;
   char * locale_string;

   // strlen gives the length of single-byte character string
   printf("Length of '%s' : %d\n", str1, strlen(str1) );

   // wstrlen gives the length of a wide character string
   wprintf(L"Length of '%s' : %d\n", wstr1, wcslen(wstr1) );

   // A multibyte string: [A] [B] [C] [katakana A] [D] [\0]
   // in Code Page 932. For this example to work correctly,
   // the Japanese language support must be enabled by the
   // operating system.
   mbstr1 = "ABC" "\x83\x40" "D";

   locale_string = setlocale(LC_CTYPE, "Japanese_Japan");

   if (locale_string == NULL)
   {
      printf("Japanese locale not enabled. Exiting.\n");
      exit(1);
   }
   else
   {
      printf("Locale set to %s\n", locale_string);
   }

   // _mbslen will recognize the Japanese multibyte character if the
   // current locale used by the operating system is Japanese
   printf("Length of '%s' : %d\n", mbstr1, _mbslen(mbstr1) );

   // _mbstrlen will recognize the Japanese multibyte character
   // since the CRT locale is set to Japanese even if the OS locale
   // isnot.
   printf("Length of '%s' : %d\n", mbstr1, _mbstrlen(mbstr1) );
   printf("Bytes in '%s' : %d\n", mbstr1, strlen(mbstr1) );  
 
}



 Its result
Length of 'Count.' : 6
Length of 'Count.' : 6
Length of 'ABCァD' : 5
Length of 'ABCァD' : 5
Bytes in 'ABCァD' : 6







You can see the same thing at this page:
http://msdn.microsoft.com/en-us/library/78zh94ax.aspx

from MSDN

'old_Coding > C/C++' 카테고리의 다른 글

[C++] Function Pointer(1) (Global function & using array)  (0) 2009.12.27
[C++] '\0' & '\n'  (0) 2009.12.25
[C++] Queue Linked List 작성  (0) 2008.12.16
[C++] STACK Linked List 작성  (0) 2008.12.16
[C++/자료구조] Simple Linked List 작성  (3) 2008.12.16