在一个字符串中查找一个宽字符串的出现次数

#include <stdio.h>
#include <wchar.h>
#include <wctype.h>

#define TEXT_SIZE   100
#define SUBSTR_SIZE  40

wchar_t *wstr_towupper(wchar_t *wstr, size_t size);   // Wide string to uppercase

int main(void)
{
  wchar_t text[TEXT_SIZE];                            // Input buffer for string to be searched
  wchar_t substr[SUBSTR_SIZE];                        // Input buffer for string sought

  wprintf(L"Enter the string to be searched (less than %d characters):/n", TEXT_SIZE);
  fgetws(text, TEXT_SIZE, stdin);
  wprintf(L"/nEnter the string sought (less than %d characters):/n", SUBSTR_SIZE);
  fgetws(substr, SUBSTR_SIZE, stdin);

  // Overwrite the newline character in each string
  int textlen = wcsnlen(text, sizeof(text)/sizeof(wchar_t));
  int substrlen = wcsnlen(substr, sizeof(substr)/sizeof(wchar_t));
  text[--textlen] = L'/0';
  substr[--substrlen] = L'/0';

  fwprintf(stdout, L"/nFirst string entered:/n%ls/n", text);
  fwprintf(stdout, L"Second string entered:/n%ls/n", substr);

  // Convert both strings to uppercase
  wstr_towupper(text, sizeof(text)/sizeof(wchar_t));
  wstr_towupper(substr, sizeof(substr)/sizeof(wchar_t));

  // Count the appearances of substr in text
  wchar_t *pwstr = text;

  int count = 0;

  while((pwstr < text + textlen - substrlen) && (pwstr = wcsstr(pwstr, substr))){
    ++count;
    pwstr += substrlen;
  }

  wprintf(L"The second string %ls found in the first%ls", count ? L"was" : L"was not", count ? L" " : L"./n");
  if(count)
     wprintf(L"%d times./n",count);
  return 0;
}

// Convert a wide string to uppercase
wchar_t *wstr_towupper(wchar_t *wstr, size_t size){
  for(size_t i = 0 ; i < wcsnlen(wstr, size) ; ++i)
    wstr[i] = towupper(wstr[i]);
  return wstr;
}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/266742.html

(0)
上一篇 2022年6月7日
下一篇 2022年6月7日

相关推荐

发表回复

登录后才能评论