使用c++的strstr函数来删除你正在搜索的子字符串的一部分

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

本文关键字:搜索 字符串 一部分 删除 strstr c++ 函数 使用      更新时间:2023-10-16

我在课堂上有一个练习问题,让我难住了,这是写一个名为strCut的函数,它接收两个c风格的字符串参数s和模式。如果模式字符串包含在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代替内循环。