簡體   English   中英

使用C ++ strstr函數刪除要搜索的子字符串部分

[英]Using the C++ strstr function to remove the part of the substring your are searching for

我在課堂上遇到一個鍛煉問題,這讓我感到很困惑,這是一個名為strCut的函數,該函數接收兩個C樣式的字符串參數s和pattern。 如果模式字符串包含在s中,則該函數將修改s,從而將s中出現的模式的第一次出現從s中刪除。 要執行模式搜索,請使用預定義的strstr函數。

到目前為止,這是我的代碼。

void strCut(char *s, char *pattern)
{
  char *x;
  char *y;
  x = strstr(s, pattern);
  cout << x; // testing what x returns
}

int main()
{

  char s[100];        // the string to be searched
  char pattern[100];  // the pattern string
  char response;           // the user's response (y/n)

do
{
  cout << "\nEnter the string to be searched ==> ";
  cin.getline(s, 100);
  cout << "Enter the pattern ==> ";
  cin.getline(pattern, 100);
  strCut(s, pattern);
  cout << "\nThe cut string is \"" << s << '"' << endl;
  cout << "\nDo you want to continue (y/n)? ";
  cin >> response;
  cin.get();
} while (toupper(response) == 'Y');

任何幫助都非常感謝。 謝謝

可以通過以下方式編寫函數

char * strCut( char *s, const char *pattern )
{
   if ( char *p = std::strstr( s, pattern ) )
   {
      char *q = p + std::strlen( pattern );
      while ( *p++ = *q++ );
   }

   return s;
}

或者可以使用函數std::memmove代替內部循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM