您可以在qt中按引号(不仅仅是引号,而是任何符号,例如'\')符号分割,只需放在\
它之前,例如:string.split("\"");
将按符号分割string
。'"'
这是一个简单的控制台应用程序来分割你的文件(最简单的解决方案是用“,”符号分割):
// opening file split.csv, in this case in the project folder
QFile file("split.csv");
file.open(QIODevice::ReadOnly);
// flushing out all of it's contents to stdout, just for testing
std::cout<<QString(file.readAll()).toStdString()<<std::endl;
// reseting file to read again
file.reset();
// reading all file to QByteArray, passing it to QString consructor,
// splitting that string by "," string and putting it to QStringList list
// where every element of a list is value from cell in csv file
QStringList list=QString(file.readAll()).split("\",\"",QString::SkipEmptyParts);
// adding back quotes, that was taken away by split
for (int i=0; i<list.size();i++){
if (i!=0) list[i].prepend("\"");
if (i!=(list.size()-1)) list[i].append("\"");
}//*/
// flushing results to stdout
foreach (QString i,list) std::cout<<i.toStdString()<<std::endl; // not using QDebug, becouse it will add more quotes to output, which is already confusing enough
其中split.csv
包含"1","hello, ""world""","and then this"
,输出为:
"1"
"hello, ""world"""
"and then this"