0

I am using QString::remove(QString) to remove a specific line from a string, but there's a small problem which is the removed string isn't really removed, it is replaced with an empty string instead. I want to remove the whole line completely.

Original String:

...
Hi there,
Alaa Joseph is here!
The above line is going to be removed :P

It's the magic of C++ :]
...

Here's what I've tried:

test1 = originalString.replace("Alaa Joseph is here!", "");
test2 = originalString.remove("Alaa Joseph is here!");  // Same result as the previous

Output:

...
Hi there,

The above line is going to be removed :P

It's the magic of C++ :]
...

As you see above, it has removed the text without removing the whole line!


I need the output to be like this:

...
Hi there,
The above line is going to be removed :P

It's the magic of C++ :]
...

I know I could just iterate through each line & do this:

QStringList list = test1.split("\n");

list.removeAt(0);
int n = list.length();
list.removeAt(n - 1);

QString noEmptyLines = list.join("\n");

But I don't want to remove all empty lines, only ones which I removed their content as this will ruin the whole format of my document.

Alaa Salah
  • 885
  • 1
  • 13
  • 23
  • "It has removed the text without removing the whole line!" NO. It has removed the text of the line UP TO the carriage return which is part of the line. "\n" is a character itself. – BaCaRoZzo Oct 28 '14 at 18:04

1 Answers1

1

Try this:

test2 = originalString.remove("Alaa Joseph is here!\n"); 

This should delete \n too and you will get correct output.

If your task has some specification you can check what you should to do. For example:

if(originalString.contains("Alaa Joseph is here!\n") )
    test2 = originalString.remove("Alaa Joseph is here!\n");
else
    if(originalString.contains("Alaa Joseph is here!"))
        test2 = originalString.remove("Alaa Joseph is here!"); 

If you are sure that the \n is always in your string, you can avoid this additional code.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Jablonski
  • 18,083
  • 2
  • 46
  • 47