如果其中有单词,请删除整行

时间:2013-07-04 15:37:50

标签: list c++-cli

我正在创建一个Windows表单程序。在表单中,我通过文本框插入一些数据,然后将其写入文件中。按下注册按钮后,我会注册一条线,依此类推。 例如:

test1|test2|test3...

test4|test5|test6...

在另一种形式中,我在文本框中键入一个单词,如果这个单词在我的文件中,我想删除该行。 示例:单词是test5,因此我将删除它所在的所有行。我会:

test1|test2|test3...

感谢Medinoc用户:

WRITE

ref class MyClass
{
public:
    String^ cognome;
    String^ nome;
    int voto_diploma;
};

//...

List<MyClass^>^ primo = gcnew List<MyClass^>();

//...

MyClass^ myObj = gcnew MyClass();
myObj->cognome = textBox1->Text;
myObj->nome = textBox2->Text;
myObj->voto_diploma = Convert::ToInt32(textBox35->Text);
primo->Add(myObj);

//...

TextWriter ^tw = gcnew StreamWriter(L"primoAnno.txt", true);
for each(MyClass^ obj in primo)
{
//You can use any character or string as separator,
//as long as it's not supposed to appear in the strings.
//Here, I used pipes.
tw->Write(obj->cognome);
tw->Write(L"|");
tw->Write(obj->nome);
tw->Write(L"|");
tw->WriteLine(obj->voto_diploma);
}
tw->Close();

READ

MyClass^ ParseMyClass(String^ line)
{
array<String^>^ splitString = line->Split(L'|');
MyClass^ myObj = gcnew MyClass();
myObj->cognome = splitString[0];
myObj->nome = splitString[1];
myObj->voto_diploma = Convert::ToInt32(splitString[2]);
return myObj;
}

DELETE

TextWriter^ tw = gcnew StreamWriter(L"primoAnno2.txt", true);
TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
String^ line;
while((line=tr->ReadLine()) != nullptr)
{
MyClass^ obj = ParseMyClass(line);
if(obj->cognome != L"cat")
    tw->WriteLine(line);
}
tr->Close();
tw->Close();
File::Delete(L"primoAnno.txt");
File::Move(L"primoAnno2.txt", L"primoAnno.txt");

但删除部分无法正常工作。你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:0)

据我所知,删除功能只检查'认知',所以如果你想要匹配的单词实际上是'nome'则不匹配。尝试修改删除功能,如下所示:

if(obj->cognome != L"cat" && obj->nome != L"cat" )
    tw->WriteLine(line);
}