使用c++的strstr函数来删除你正在搜索的子字符串的一部分
Using the C++ strstr function to remove the part of the substring your are searching for
我在课堂上有一个练习问题,让我难住了,这是写一个名为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
代替内循环。
相关文章:
- 在对象数组中搜索字符串并返回相应值的函数
- 在 QTextEdit 中搜索字符串
- C++ 中用于搜索字符串模式的正则表达式
- 如何在文件中搜索字符串并打印包含该字符串的行
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- 从文件中提取的数据中的C 搜索字符串失败
- 在数组中搜索字符串的所有术
- 在 main 中搜索字符串的结尾时出现分段错误,但不在函数C++中搜索
- 在字符串中搜索字符串序列
- c++搜索字符串列表中的特定字符串
- 从文件中读取一行,并在其中搜索字符串(c++)
- 在向量中搜索C++字符串s中的单词
- 在另一个进程的内存中搜索字符串的每个匹配项
- 当搜索字符串有空格时查找字符串
- 在结构向量中搜索字符串C++
- 搜索字符串中的第一个字符不同于"X"
- 搜索字符串(只查找完全匹配的字符串,不忽略大写或小写字符
- 如何在C++中搜索字符串数组
- 替换特定位置后出现的所有搜索字符串
- 搜索字符串以使用递归查找另一个字符串