C++使用string类编写一个简单的文本编辑程序,可以实现基本的插入、删除、查找、替换等功能。
时间: 2024-05-29 07:08:34 浏览: 4
可以使用以下代码作为基础:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
char choice;
while (true)
{
cout << "Enter a choice: " << endl;
cout << "I - Insert text" << endl;
cout << "D - Delete text" << endl;
cout << "F - Find text" << endl;
cout << "R - Replace text" << endl;
cout << "Q - Quit" << endl;
cin >> choice;
switch (choice)
{
case 'I':
{
string insertText;
cout << "Enter text to insert: ";
cin >> insertText;
int position;
cout << "Enter position to insert at: ";
cin >> position;
text.insert(position, insertText);
cout << "Text after insert: " << text << endl;
break;
}
case 'D':
{
int start, length;
cout << "Enter start position: ";
cin >> start;
cout << "Enter length to delete: ";
cin >> length;
text.erase(start, length);
cout << "Text after delete: " << text << endl;
break;
}
case 'F':
{
string searchText;
cout << "Enter text to find: ";
cin >> searchText;
int position = text.find(searchText);
if (position != string::npos)
{
cout << "Found at position: " << position << endl;
}
else
{
cout << "Not found" << endl;
}
break;
}
case 'R':
{
string searchText, replaceText;
cout << "Enter text to replace: ";
cin >> searchText;
cout << "Enter replacement text: ";
cin >> replaceText;
int position = text.find(searchText);
if (position != string::npos)
{
text.replace(position, searchText.length(), replaceText);
cout << "Text after replace: " << text << endl;
}
else
{
cout << "Not found" << endl;
}
break;
}
case 'Q':
{
return 0;
}
default:
{
cout << "Invalid choice" << endl;
break;
}
}
}
return 0;
}
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)