zoukankan      html  css  js  c++  java
  • windows,c,string

    http://zetcode.com/gui/winapi/strings/


     

    The string length

    One of the most common requirements is to figure out the length of the string. The lstrlen()function returns the lenght of the specified string in characters. It does not count the terminating null character.

    int WINAPI lstrlenA(LPCSTR lpString);
    int WINAPI lstrlenW(LPCWSTR lpString);
    

    The ANSI and the UNICODE functions take the string as a parameter and return the number of characters in the string.

    #include <windows.h>
    #include <wchar.h>
    
    int wmain(void) 
    {
      char *name = "Jane";
      wchar_t *town = L"Bratislava";
    
      wprintf(L"The length of the name string is %d
    ", lstrlenA(name));
      wprintf(L"The town string length is %d
    ", lstrlenW(town));
    
      return 0;
    }
    

    We compute the length of two strings. The lstrlen() function is in fact a macro to either lstrlenA()or lstrlenW(). The first is used for ANSI strings, the second for wide strings.

    wprintf(L"The town string length is %d
    ", lstrlenW(town));
    

    We print the length of the L"Bratislava" string using the lstrlenW() function.

    C:winapiexamples2stringsStringLength>string_length.exe
    The name string length is 4
    The town string length is 10
    

    Output of the program.

    Concatenating strings

    The lstrcatW() function appends one string to another string.

    LPWSTR WINAPI lstrcatW(LPWSTR lpString1, LPCWSTR lpString2);
    

    The first parameter is the buffer which should contain both strings. It must be large enough to contain both of them. Including the null terminating character. The return value is a pointer to the buffer.

    #include <windows.h>
    #include <wchar.h>
    
    int main(void) 
    {
      wchar_t *s1 = L"ZetCode, ";
      wchar_t *s2 = L"tutorials ";
      wchar_t *s3 = L"for ";
      wchar_t *s4 = L"programmers.
    ";
    
      int len = lstrlenW(s1) + lstrlenW(s2) 
          + lstrlenW(s3) + lstrlenW(s4);
      wchar_t buff[len+1];
      
      lstrcpyW(buff, s1);
      lstrcatW(buff, s2);
      lstrcatW(buff, s3);
      lstrcatW(buff, s4);
    
      wprintf(buff);    
    
      return 0;
    }
    

    In the example, we will concatenate four strings.

    wchar_t *s1 = L"ZetCode, ";
    wchar_t *s2 = L"tutorials ";
    wchar_t *s3 = L"for ";
    wchar_t *s4 = L"programmers.
    ";
    

    These are the strings that we are going to concatenate.

    int len = lstrlenW(s1) + lstrlenW(s2) 
        + lstrlenW(s3) + lstrlenW(s4);
    

    We compute the length of the four strings using the lstrlenW() function.

    wchar_t buff[len+1];
    

    We create a buffer to hold the final string. Note that we add 1 to include the null character.

    lstrcpyW(buff, s1);
    

    We copy the first string to the buffer using the lstrcpyW() function.

    lstrcatW(buff, s2);
    lstrcatW(buff, s3);
    lstrcatW(buff, s4);
    

    We append the remaining strings with the lstrcatW() function.

    C:winapiexamples2stringsCat>Cat.exe
    ZetCode, tutorials for programmers.
    

    Output of the program.

    Converting characters

    We have two methods for converting characters either to uppercase or to lowercase. The CharLowerW() function converts a character string or a single character to lowercase. The CharUpperW()function converts a character string or a single character to uppercase. If the operand is a character string, the function converts the characters in place. In other words, they are modified.

    LPWSTR WINAPI CharLowerW(LPWSTR lpsz);
    LPWSTR WINAPI CharUpperW(LPWSTR lpsz);
    

    The functions modify the strings in place and return a pointer to the modified string.

    #include <windows.h>
    #include <wchar.h>
    
    #pragma comment(lib, "User32.lib")
    
    int wmain(void) 
    {
      wchar_t str[] = L"Europa";
    
      CharLowerW(str);
      wprintf(L"%ls
    ", str);
    
      CharUpperW(str);
      wprintf(L"%ls
    ", str);    
    
      return 0;
    }
    

    We have one string which we convert to lowercase and uppercase.

    CharLowerW(str);
    wprintf(L"%ls
    ", str);
    

    We convert the str string to lowercase with the CharLowerW() method. The string is modified in place.

    C:winapiexamples2stringsUpperLower>UpperLower.exe
    europa
    EUROPA
    

    Output of the UpperLower.exe program.

    Comparing strings

    We often need to compare two strings. The lstrcmpW() function compares two strings. It returns 0 if the strings are equal. The comparison is case sensitive. This means that "Cup" and "cup" are two different strings. The lstrcmpiW() yields case insensitive string comparison. For this function, "Cup" and "cup" are equal.

    int WINAPI lstrcmpW(LPCWSTR lpString1, LPCWSTR lpString2);
    int WINAPI lstrcmpiW(LPCWSTR lpString1, LPCWSTR lpString2);
    

    The functions take two strings as parameters. The return value indicates the equality of the strings. 0 value is returned for equal strings.

    #include <windows.h>
    #include <wchar.h>
    
    #define STR_EQUAL 0
    
    int wmain(void)
    {
      wchar_t *s1 = L"Strong";
      wchar_t *s2 = L"strong";
      
      if (lstrcmpW(s1, s2) == STR_EQUAL) {
          wprintf(L"%ls and %ls are equal
    ", s1, s2);
      } else {
          wprintf(L"%ls and %ls are not equal
    ", s1, s2);
      }
    
      wprintf(L"When applying case insensitive comparison:
    ");
      if (lstrcmpiW(s1, s2) == STR_EQUAL) {
          wprintf(L"%ls and %ls are equal
    ", s1, s2);
      } else {
          wprintf(L"%ls and %ls are not equal
    ", s1, s2);
      }
    
      return 0;
    }
    

    We have two strings. We compare them using both case sensitive and case insensitive string comparison.

    if (lstrcmpW(s1, s2) == STR_EQUAL) {
        wprintf(L"%ls and %ls are equal
    ", s1, s2);
    } else {
        wprintf(L"%ls and %ls are not equal
    ", s1, s2);
    }
    

    If the lstrcmpW() function returns STR_EQUAL, which is defined to 0, then we print to the console that the two strings are equal. Otherwise we print that they are not equal.

    C:winapiexamples2stringsCompare>Compare.exe
    Strong and strong are not equal
    When applying case insensitive comparison:
    Strong and strong are equal
    

    The Compare.exe program gives the above output.

    Filling a buffer

    Filling a buffer with formatted data is essential in C programming. The wsprintfW() function writes formatted data to the specified buffer.

    #include <windows.h>
    #include <wchar.h>
    
    #pragma comment(lib, "User32.lib")
    
    int wmain(void)
    {
      SYSTEMTIME st;
      wchar_t buff[50];
    
      GetLocalTime(&st);
      wsprintfW(buff, L"Today is %lu.%lu.%lu
    ", st.wDay, 
          st.wMonth, st.wYear);
    
      wprintf(buff);
    
      return 0;
    }
    

    We build a string which is filled with the current date.

    wchar_t buff[50];
    

    In this particular case we can safely assume that the string will not exceed 50 characters.

    GetLocalTime(&st);
    

    The GetLocalTime() function retrieves the current local date and time.

    wsprintfW(buff, L"Today is %lu.%lu.%lu
    ", st.wDay, 
        st.wMonth, st.wYear);
    

    The wsprintfW() fills the buffer with a wide string. Arguments are copied to the string according to the format specifier.

    wprintf(buff);
    

    The contents of the buffes is printed to the console.

    C:winapiexamples2stringsData2Buffer>Data2Buffer.exe
    Today is 22.9.2012
    

    Output of the example.

    Character types

    Characters have various types. They can be digits, spaces, letters, punctuation or control characters.

    BOOL WINAPI GetStringTypeW(DWORD dwInfoType, LPCWSTR lpSrcStr,
        int cchSrc, LPWORD lpCharType);
    

    The GetStringTypeW() function retrieves character type information for the characters in the specified Unicode string. The first parameter is a flag specifying the info types.

    FlagMeaning
    CT_CTYPE1 Retrieve character type information
    CT_CTYPE2 Retrieve bidirectional layout information
    CT_CTYPE3 Retrieve text processing information
    Table: Character info types

    The second parameter is the Unicode string for which to retrieve the character types. The third parameter is the size of the string. The final parameter is a pointer to an array of 16-bit values. The length of this array must be large enough to receive one 16-bit value for each character in the source string.

    The GetStringTypeW() function returns a value, which is a combination of types. We can query a specific type with the & operator.

    ValueMeaning
    C1_DIGIT Decimal digits
    C1_SPACE Space characters
    C1_PUNCT Punctuation
    C1_CNTRL Control characters
    C1_ALPHA Any linguistic character
    Table: Partial list of character types
    #include <windows.h>
    #include <wchar.h>
    
    int wmain(void) 
    {
      wchar_t str[] = L"7 white, 3 red roses.
    ";
    
      int alphas = 0;
      int digits = 0;
      int spaces = 0;
      int puncts = 0;
      int contrs = 0;
    
      int size = lstrlenW(str);
      WORD types[size];
    
      BOOL rv = GetStringTypeW(CT_CTYPE1, str, size, types);
    
      if (!rv) {
        wprintf(L"Could not get character types (%ld)", GetLastError());
        return EXIT_FAILURE;
      }
    
      for (int i=0; i<size; i++) {
    
        if (types[i] & C1_ALPHA) {
          alphas++;
        }
    
        if (types[i] & C1_DIGIT) {
          digits++;
        }
    
        if (types[i] & C1_SPACE) {
          spaces++;
        }
    
        if (types[i] & C1_PUNCT) {
          puncts++;
        }
    
        if (types[i] & C1_CNTRL) {
          contrs++;
        }
      }
    
      wprintf(L"There are %ld letter(s), %ld digit(s), "
        L"%ld space(s), %ld punctuation character(s), "
        L"and %ld control character(s)
    ", alphas, digits, 
        spaces, puncts, contrs);  
    
      return 0;
    }
    

    We have a short sentence. The GetStringTypeW() function is used to determine the character types of the string.

    wchar_t str[] = L"7 white, 3 red roses.
    ";
    

    This is a short sentence consisting of various wide characters.

    int alphas = 0;
    int digits = 0;
    int spaces = 0;
    int puncts = 0;
    int contrs = 0;
    

    These variables will be used to count letters, digits, spaces, punctuation and control characters.

    int size = lstrlenW(str);
    WORD types[size];
    

    We get the size of the string and create and array of values. The size does not include the null terminating character. We can add 1 to include it. It will be counted as a control character.

    BOOL rv = GetStringTypeW(CT_CTYPE1, str, size, types);
    

    We get the character types of the sentence. The types array is filled with character type values.

    if (types[i] & C1_DIGIT) {
      digits++;
    }
    

    If the value contains the C1_DIGIT flag, we increase the digits counter.

    C:winapiexamples2stringsLetters>Letters.exe
    There are 13 letter(s), 2 digit(s), 5 space(s), 2 punctuation character(s), and
    1 control character(s)
    

    Output of the example.

    The CRT string functions

    There are also lots of string functions in the C Run-Time (CRT) library. Many of them are duplicates to the Winapi functions. It is a matter of opinion which types of string functions should be used. The CRT functions have some small overhead since they call Winapi functions underneath.

    #include <windows.h>
    #include <wchar.h>
    
    #define STR_EQUAL 0
    
    int wmain(void)
    {
      wchar_t str1[] = L"There are 15 pines";
    
      wprintf(L"The length of the string is %ld characters
    ", 
        wcslen(str1));
    
      wchar_t buf[20];
      wcscpy(buf, L"Wuthering");
      wcscat(buf, L" heights
    ");
      wprintf(buf);
    
      if (wcscmp(L"rain", L"rainy")== STR_EQUAL) {
        wprintf(L"rain and rainy are equal strings
    ");
      } else {
        wprintf(L"rain and rainy are not equal strings
    ");
      } 
    
      return 0;
    }
    

    In the example we present a few string functions from the CRT library.

    wprintf(L"The length of the string is %ld characters
    ", 
      wcslen(str1));
    

    The wcslen() returns the number of characters in the string.

    wcscpy(buf, L"Wuthering");
    

    The wcscpy copies a string to a string buffer.

    wcscat(buf, L" heights
    ");
    

    The wcscat() function appends a string to a string buffer.

    if (wcscmp(L"rain", L"rainy")== STR_EQUAL) {
      wprintf(L"rain and rainy are equal strings
    ");
    } else {
      wprintf(L"rain and rainy are not equal strings
    ");
    } 
    

    The wcscmp() compares two string.

    C:winapiexamples2stringsCRTStrings>CRTStrings.exe
    The length of the string is 18 characters
    Wuthering heights
    rain and rainy are not equal strings
    

    Output of the example.

    In this part of the Winapi tutorial, we have worked with strings.

  • 相关阅读:
    Discuz论坛自动发帖机
    C#测试数据库连接是否成功
    JS重写提示框(confirm)
    随笔 选择
    随笔 诚实
    web项目经理手册【1】版本控制流程
    Asp.net多层架构中的变量引用与传递
    ASP.NET跨页面传值技巧总结
    web项目经理手册【3】Code Review
    web项目经理手册【7】项目经理需要铭记在心的话
  • 原文地址:https://www.cnblogs.com/threef/p/3261942.html
Copyright © 2011-2022 走看看