[英]finding and replacing word in string
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[80];
char find[10];
char change[10];
char* pstr;
char* temp = new char[80];
cin.getline(str, 80);
cin.getline(find,10);
cin.getline(change,10);
pstr =strstr(str,find);
int a = str.find(pstr);
int len;
len = strlen(find);
str.replace(a,len,change);
delete []temp;
cout<< str<< endl;
return 0;
}
The error message is: 错误消息是:
Main.cpp: In function 'int main()': Main.cpp:18:15: error: request for member 'find' in 'str', which is of non-class type 'char [80]' int a = str.find(pstr); ^ Main.cpp:21:7: error: request for member 'replace' in 'str', which is of non-class type 'char [80]' str.replace(a,len,change); ^
For example, 例如,
what is your nam / nam / name
the output is 输出是
'what is your name'
what is matter?
The statement str.find(pstr);
语句str.find(pstr);
means Call the member function find
of the object str
with pstr
as argument . 表示以pstr
作为参数调用对象str
的成员函数find
。 If you are not sure to completely understand this sentence, I'd suggest you to find a good C++ book . 如果您不确定是否完全理解这句话,建议您找一本不错的C ++书 。
The thing is, str
has type char[80]
, which is not an object of class-type with an available member function find
. 问题是, str
类型为char[80]
,这不是具有可用成员函数find
的class-type对象。 It's a C-style array, not suitable for OOP. 这是C样式的数组,不适合OOP。
What you need is std::string
: 您需要的是std::string
:
#include <string>
std::string str;
/* set str */
auto pos = str.find(pstr);
Here is the doc of std::string::find()
. 这是std::string::find()
的文档。
Use std::string
instead of char[N]
. 使用std::string
代替char[N]
。
The char[80]
type is a fundamental type and doesn't have functions. char[80]
类型是基本类型,没有功能。
For the getline, you will need to change it to: 对于getline,您需要将其更改为:
std::getline(std::cin, str);
int main()
{
char str[80];
char find[10];
char change[10];
char* pstr;
char* temp = new char[80];
cin.getline(str, 80);
cin.getline(find,10);
cin.getline(change,10);
pstr = strstr(str,find);
std::string newStr = str;
int a = newStr.find(pstr);
int len;
len = strlen(find);
newStr.replace(a,len,change);
delete []temp;
cout<< newStr << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.