从从 & 开头然后包含 23 个字符的文件中删除字符串

Remove a String from a file which starts from a & and then has 23 characters in it

本文关键字:文件 删除 字符串 字符 开头 然后 包含 从从      更新时间:2023-10-16

我正在开发一个小程序来实现一些目标。

因此,我使用该程序获取了一个文件,但它有一个以"&"开头的字符串在很多地方。

我将解释我问题中最细微的部分。我有一个字符串,在这个字符串中我想删除一些字符,它以'&'开头后面跟着23位数字。

请建议我如何做到这一点。

好吧,您需要创建一个循环来读取文件中的所有字符串:

std::ifstream fin( "input.txt" );
std::string line;
std::getline( fin, line );
while( !fin.eof() ) {
    getline( fin, line );
}

当然,您不能就地修改文件。您需要将输入文件的内容写入另一个文件中。

std::ifstream fin( "input.txt" );
std::ofstream fout( "output.txt" );
std::string line;
std::getline( fin, line );
while( !fin.eof() ) {
    fout << line << std::endl;
    getline( fin, line );
}

剩下的唯一一件事就是找到那些带有"&"的字符串并消除随后的23个字符。

std::ifstream fin( "input.txt" );
std::ofstream fout( "output.txt" );
std::string line;
std::getline( fin, line );
while( !fin.eof() ) {
    unsigned int pos = line.find( '&' );
    if ( pos != string::npos ) {
        string line2 = line.substring( 0, pos -1 );
        line2 += line.substring( pos + 23 );
        line = line2;
    }
    fout << line << std::endl;
    std::getline( fin, line );
}

最后,您需要去掉input.txt。希望这能有所帮助。

您应该使用string.find和string.replace.

这里的代码示例http://www.cplusplus.com/reference/string/string/find/显示了一种完美的方法:)

std::string content = "some long string";
std::string string_to_replace = "some ";
str.replace(content.find(string_to_replace),string_to_replace.length(),"");

这将在内容中找到string_to_replace,并将其替换为"。当然,这是假设您在写入文件之前解决了问题。在本例中,它将产生"长字符串"。