views:

36

answers:

2

Hi,

message.Text() is a QString.

I want to remove some text.

The text can be:

  1. Normal: "This is a text"
  2. With a label: "<label1>something</label1>This is a text"

First, I find if the text has the label:

!message.Text().contains("<label1>", Qt::CaseInsensitive))

So, if it has, I want to remove the first part, to have a normal text "This is a text".

I tried this:

first=message.Text().indexOf("<label1>");
last=message.Text().lastIndexOf("</label1>");
message.Text().remove(first,last);

But I got Compiler Error C2663.

I also know that the message.Text().remove(QChar('<label1'), Qt::CaseInsensitive); is another way to do it. But in my case, the part between the label is unkwnow.

It can be <label1>something</label1> or <label1>oisdioadj</label> or <label1>7</label1>....

Any idea?

Regards.

+1  A: 

My advice here: keep things simple in your code, it will help making things simple in your head.

It seems what you want to achieve is more related to strings, than to label.

I suggest you get the text from your label, then work on it independently, then associate it back to your label:

QString text = message.text();

/* Do whatever you need to do here with text */

message.setText(text);

Also, the error you're having is probably due to the fact that you try to modify directly message.text() which is a const reference: obviously you can't modify something that is const.

I believe what you try to achieve can be done using QString::replace(). You'll have to use regular expressions for that, so if you're not familiar with it, it might be difficult.

ereOn
Thanks for your reply. You are right with the const, however I can not do message.setText(Text). My class hasn't setText.text() returns the QString that I want to use.In that string I can have <hair>blonde</hair>Do you like my hair?Where I have to take blonde parameter out, and save in the text only: Do you like my hair?But blonde, is just an example, they are a lot that I can not controll. So all between <hair> and </hair> must be removed.
andofor
+2  A: 

Try the following:

#include <iostream>
using std::cout; using std::endl;
#include <QString>

int main()
{
  QString message = "<label1>something</label1>This is a test";
  const QString labelClose = "</label1>";
  const int labelCloseSize = labelClose.size();

  cout << "message: " << qPrintable(message) << endl;

  const int closePosition = message.lastIndexOf(labelClose);
  QString justText = message.remove(0, closePosition + labelCloseSize);
  cout << "just text: " << qPrintable(justText) << endl;
}
Bill
Thanks :D That's perfect.What about if I want to use a HTML/XML parser?
andofor
@nowf: Try Qt's XML parser: http://doc.trolltech.com/4.6/qxmlstreamreader.html
Bill