Reputation: 45
I'm trying to replace the text of a specific line, but got no success. (i'd searched a lot, but i don't found nothing)
something like:
hello
my
friend!
replacing line 2 to some text:
hello
AEEEHO NEW LINE TEXT
friend!
I created a QStringList and tried to read the text line by line and add to this list by changing just the line, but without success.
int line = 1; // to change the second line
QString newline = "my new text";
QStringList temp;
int i = 0;
foreach(QString curlineSTR, internalCode.split('\n'))
{
if(line == i)
temp << newline;
else
temp << curlineSTR;
i++;
}
internalCode = "";
foreach(QString txt, temp)
internalCode.append(QString("%1\n").arg(txt));
Upvotes: 0
Views: 679
Reputation: 2881
I belive that you are looking for QRegExp
to deal with newline and do something like this:
QString internalcode = "hello\nmy\nfriend!";
int line = 1; // to change the second line
QString newline = "another text";
// Split by newline command
QStringList temp = internalcode.split(QRegExp("\n|\r\n|\r"));
internalcode.clear();
for (int i = 0; i < temp.size(); i++)
{
if (line == i)
internalcode.append(QString("%0\n").arg(newline));
else
internalcode.append(QString("%0\n").arg(temp.at(i)));
}
//Use this to remove the last newline command
internalcode = internalcode.trimmed();
qDebug() << internalcode;
And the output:
"hello
another text
friend!"
Upvotes: 2