0

I have an exercise question in class that has me stumped which is write a function named strCut that receives two C-style string parameters s and pattern. If the pattern string is contained in s, then the function modifies s such that the first occurrence of pattern that appears in s is removed from s. To perform the pattern search, use the predefined strstr function.

Here is my code as of now.

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');

Any help is very appreciated. Thanks

user2027757
  • 13
  • 1
  • 6
  • Since this appears to be homework I am only going to give a hint: `strstr` does half of the job. The remainder of the job will be done by `memmove`. (It may *appear* that `memcpy` or `strcpy` can also do that part, but that is incorrect.) You will also need `strlen`. – zwol Mar 26 '14 at 00:08

1 Answers1

0

The function can be written for example the following way

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;
}

Or there could be used function std::memmove instead of the inner loop.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    -1 `strcpy` has undefined behavior for overlapping strings. Would -1 again for giving out complete answers to homework, (this has been scientifically demonstrated to inhibit learning), and -1 yet a third time for the abominable practice of putting spaces on the inside of parentheses, if only I could. – zwol Mar 26 '14 at 00:25
  • 1
    C11 section 7.24.2.3 (specification of `strcpy`): "If copying takes place between objects that overlap, *the behavior is undefined*." Identical language for `memcpy`, `strncpy`, `strcat`, `strncat`. Only `memmove` is valid for this use case. – zwol Mar 26 '14 at 00:30
  • If you acknowledge the error please correct the code so as not to mislead future readers. (I will not retract the -1, though, because of the giving out complete answers to homework.) – zwol Mar 26 '14 at 00:36
  • @Zack I could write code manually in fact the same as the logic of strcpy. – Vlad from Moscow Mar 26 '14 at 00:37
  • @Zack Do you mean the first function definition? – Vlad from Moscow Mar 26 '14 at 01:01