我在课堂上有一个运动问题让我难倒,写了一个名为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');
非常感谢任何帮助。谢谢
答案 0 :(得分:0)
该功能可以通过以下方式编写
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
而不是内循环。