创建程序以从给定的.txt文件中查找文本,替换并计算单词

Create program to find a text from given .txt file , replace and count the words

本文关键字:文本 查找 替换 单词 计算 文件 程序 txt 创建      更新时间:2023-10-16

我的老师要求我创建这个程序,但我只知道如何做B任务。 他给了我一个示例文本,并告诉我输入它然后做一些操作(下面(。我查找任务 A,但他说我们需要像这样做代码。 我花了几天时间写《从控制结构到对象C++》一书,这是他课程所需的,但我找不到与"查找字符串"相关的章节。

string text = "The aa Art of Computer Programming";
int pos = 0;
string target = "aa";
pos = text.find(target, 0);
}

但问题是我不知道如何更改pos = text.find(target, 0);=>pos = "input file ?".find(target,0).

a. 搜索文本。程序从用户接收搜索词,搜索文件的内容 并返回是否找到匹配的单词以及匹配的单词数量。

b. 搜索和替换文本。程序从 用户,它将文件内容中的匹配词替换为替换词。

c. 确定字数。

d. 确定字符数(包括空格(

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
string strTarget = " "; //String to search
string strNew = " ";    //String To re
ifstream filein("test.txt"); //File to read from
ofstream fileout("replaced.txt"); //Temporary file
int pos = 0;

int menuItem = 0;
cout << "What do you want to do today ?" << endl;
cout << "1. Search a text " << endl;
cout << "2. Search and replace the text " << endl;
cout << "3. Determine number of word" << endl;
cout << "4. Determine number of character " << endl;
cin >> menuItem;

switch (menuItem)
{
case 1:// search
system("cls");
cout << "Please enter the text you want to search" << endl;
cin >> strTarget;
break;
case 2: // search and replace

cout << " Tell me the text you want to replace " << endl;
cin >> strTarget;
cout << " So what It's suppose to be ? " << endl;
cin >> strNew;
if (!filein || !fileout) //if both files are not available
{
cout << "Error opening files!" << endl;
return 1;
}
string strTemp;
//bool found = false;
while (filein >> strTemp)//it will check line from test to strTemp string
{
if (strTemp == strTarget)//if your word found then replace
{
strTemp = strNew;
//found = true;
}
strTemp += " ";
fileout << strTemp;//output everything to fileout(temp.txt)
//if(found) break;
}
return 0;
}
}
  • 代码的注释不是真的正确,因为我稍微更改了名称。 我知道这对大多数程序员来说有点荒谬,但我是 CS 的新手,而且肯定我对书中的任何代码都有麻烦。请帮助我,而不是粗鲁。非常感谢! 我希望我的大学有CS的导师,但不知何故,他们负担不起CS导师。这就是为什么我需要你们的帮助.

任务 A:计算字符串中出现的字符数
C++任务 B:如何替换字符串中出现的所有字符?
任务C:C++函数来计算字符串中的所有单词

对于最后一个任务,您只需循环访问字符串中的所有字符,直到达到空字符,每次递增一个计数器。