Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top