C语言删除文件中一定的字符

已知一些学生的姓名,成绩,还有邮箱,我们要把现在这个文档里面学生的邮箱全部删掉,然后输出到一个新的文档里。
该如何判断是否是邮箱然后进行删除呢?

我按照我的思路简单用C++实现了一下,虽然有些粗糙,但我觉得可以给你一些启发。我的思路如下:

  1. 首先,创建一个链表来存放每一个学生的信息。我们不知道一共有多少个学生,所以只能使用链表。(为什么不使用std::vector?因为vector的扩容会导致相同数据被拷贝多次,而我们要做的工作不需要随机访问数据,所以链表是最好的选择);
  2. 逐行读取文件(假设每个学生信息都在一行),然后将每一行作为一个字符串push到链表中;
  3. 重点:遍历链表中的每一个字符串,找到字符'@'的下标(每个邮箱名都需要一个@符号)。然后以这个下标为起点,分别往前和往后遍历字符串,直到达到 空格、0、或者字符串长度-1。这样你就确定了邮箱在整个字符串中的位置。接下来你需要想办法将这段字符串删掉。
  4. 最后,将链表中修改过后的字符串以此输出到新文件即可。

这是我的c++代码,希望可以帮到你(点个采纳吧!QAQ)
输入文件:

tom 90 tom3278@163.com
lily 80 lily2154@qq.com
cat 79 cateatmouse@gmail.com

cateatmouse@gmail.com cat 79
tom3278@163.com tom 90 
lily2154@qq.com lily 80 

cat cateatmouse@gmail.com 79
tom tom3278@163.com 90 
lily lily2154@qq.com 80 

代码:

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

void read(const std::string& path, std::list<std::string>& list)
{
    std::ifstream fin;
    fin.open(path, std::ios::in);
    if(!fin.is_open())
    {
        std::cout << "Cannot find the file" << '\n';
        return;
    }
    std::string buff;
    while(std::getline(fin, buff))
        list.push_back(std::move(buff));
    fin.close();
}

void extract(std::list<std::string>& list)
{
    for(std::string& str : list)
    {
        int idx = 0;
        for(; idx < str.length(); idx++)
        {
            if(str[idx] == '@')
                break;
        }
        int start = idx, end = idx;
        // find the start index
        for(; start >= 0; start--)
        {
            if(str[start] == ' ' || start == 0)
                break;
        }
        // find the end index
        for(; end < str.length(); end++)
        {
            if(str[end] == ' ')
                break;
        }
        str.erase(
            str.begin() + start, 
            str.begin() + end
        );
    }
}

void write(const std::string& path, const std::list<std::string>& list)
{
    std::ofstream fout;
    fout.open(path, std::ios::out);
    if(!fout.is_open())
    {
        std::cout << "Cannot find the file" << '\n';
    }
    for(const std::string& str : list)
        fout << str << '\n';
    fout.close();
}

int main()
{
    std::list<std::string> list;
    read("test.txt", list);
    extract(list);
    write("test1.txt", list);
}

输出文件:

tom 90
lily 80
cat 79

 cat 79
 tom 90 
 lily 80 

cat 79
tom 90 
lily 80 
有效合法邮箱格式:
用户名@邮件服务器

具体表现如下:

当且仅当只有一个@ 
要含有.符号
而且@符号要在. 号的前面
并且@的前面不能为空,必须有字符串
@和.都不能在末尾。