جستجوری رشته در فایل و اعمال حذف و ویرایش بر آن - هفت خط کد انجمن پرسش و پاسخ برنامه نویسی

جستجوری رشته در فایل و اعمال حذف و ویرایش بر آن

0 امتیاز

سلام دوستان

سوالی در مبحث فایل و رشته داشتم.

فکر کنید در حال حاضر یه متن بلند در فایلی بنام x داریم 

ما میخواهیم که کلمه علی را پیدا کرده در این متن  و با کلمه  رضا جایگزین کند یا اصلا علی را حذف کند.

میخواستم ببینم جستجوی این رشته چجوره؟

میخواهم هر تغییری بتونم تو این متن بدم .

نکته مهم:

بعد از این که خواستیم تغییر ایجاد بشه فقط اونجا تغییر ایجاد بشه 

چون خودم یکبار انجام دادم ....و بجای جایگزینی کلمه ........متنو پاک و فقط رضا چاپ  میکنه

ممنون جواب بدید.

bool ADD_NEW(){
	int n_person, choice;
	string name, number;
	cout<<"| How many contacts you want to add : \n";
	cin >>n_person;
	system("CLS");
	for (int i = 0; i < n_person; i++){
		cout<<"| Enter you contact name : \n";
		cin.ignore();
		getline(cin, name);
		contact.name.push_back(name);
		cout<<"| Enter your contact number : \n";
		cin >>number;
		contact.number.push_back(number);
		system("CLS");
	}
	
	//write to file
	write_file_stream.open("testfile.txt", ios::trunc);
	for(int i = 0; i < contact.name.size(); i++){
		write_file_stream <<"-------------------------\n";
		write_file_stream << contact.name[i] <<endl;
		write_file_stream << contact.number[i] << endl;
	}
	write_file_stream.close();

 

سوال شده دی 22, 1397  بوسیله ی m_issaq_m (امتیاز 18)   1 1 3
ویرایش شده دی 25, 1397 بوسیله ی m_issaq_m
کد خودتون رو قرار بدید
قرار داده شد ..........حالا جواب بدید

1 پاسخ

+2 امتیاز
 
بهترین پاسخ
#include <fstream>
#include <sstream>
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
	size_t start_pos = 0;
	while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
		str.replace(start_pos, from.length(), to);
		start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
	}
	return str;
}
int main(int argc, char *argv[])
{
	const std::string file_name = R"(D:\readme.txt)";
	std::ifstream filei(file_name);

	std::string line;
	std::string src_str = "ali";
	std::string dst_str = "reza";


	std::string wholeFile;

	if (filei.is_open())
	{
		std::stringstream buffer;
		buffer << filei.rdbuf();
		wholeFile = buffer.str();
		filei.close();

		
		wholeFile = ReplaceAll(wholeFile, src_str, dst_str);
		
		std::ofstream fileo(file_name);
		std::stringstream ss;
		ss.str(wholeFile);
		fileo << ss.rdbuf();
		fileo.close();

	}

}
	

 

پاسخ داده شده دی 25, 1397 بوسیله ی farnoosh (امتیاز 8,362)   20 44 59
انتخاب شد آذر 14, 1399 بوسیله ی عباس مولایی
ممنون از جوابتون
...