【问题标题】:Using the C++ strstr function to remove the part of the substring your are searching for使用 C++ strstr 函数删除您正在搜索的子字符串部分
【发布时间】:2014-05-04 03:23:13
【问题描述】:

我在课堂上有一个练习题让我很困惑,那就是编写一个名为 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');

非常感谢任何帮助。谢谢

【问题讨论】:

  • 由于这似乎是家庭作业,我只提供一个提示:strstr 完成了一半的工作。其余工作将由memmove 完成。 (可能显示memcpystrcpy 也可以完成该部分,但这是不正确的。)您还需要strlen

标签: c++ function strcpy strcat strstr


【解决方案1】:

函数可以写成例如下面的方式

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代替内部循环。

【讨论】:

  • -1 strcpy 对重叠字符串有未定义的行为。如果我可以的话,我会再次 -1 以给出完整的家庭作业答案,(科学证明这会抑制学习),如果我可以的话,第三次会因为在括号内放置空格的可恶做法而第三次。跨度>
  • C11 第 7.24.2.3 节(strcpy 的规范):“如果复制发生在重叠的对象之间,行为未定义。” memcpystrncpystrcatstrncat 的语言相同。只有 memmove 对此用例有效。
  • 如果您承认错误,请更正代码,以免误导未来的读者。 (不过,我不会收回 -1,因为给出了完整的家庭作业答案。)
  • @Zack 我可以手动写代码其实和strcpy的逻辑一样。
  • @Zack 你的意思是第一个函数定义吗?
猜你喜欢
  • 1970-01-01
  • 2012-08-16
  • 2021-10-21
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多