PDA

View Full Version : change the positions of characters in a string



arunvv
9th January 2008, 02:53
Hi

I want to change the positions of characters in a string.
Ex: QString x = "341256";
I want to Change the x string from "341256" to "123456";

How can I change the character positions within a string.

Thanks & Regards,
Arun.

wysota
9th January 2008, 10:58
You mean you want to sort it or make an arbitrary change?

This might just work:

QString str = "341256";
QChar *dat = str.data();
qSort(dat, dat+str.length());

If you want arbitrary changes then swap characters manually.

QString str="342516";
qSwap(str[2], str[3]);

arunvv
10th January 2008, 00:58
Thanks for your reply.
I gave me error if I am trying to swap characters using qswap. It seems to me qswap is used to swap a whole string, not to swap individual characters inside the string.

So I resolved the issue by converting QString to Std C++ string and using the method which you stated in reply i.e. swapping.

Resolved as Shown here:

classname::function()
{
....
QString str = "341256";
char * str1;
str1 = (char *)Q_date.toAscii().constData();
swap( str1[0], str1[2] );
swap( str1[1], str1[3] );
str = (const char *)str1; // Now str has string "123456"

....
}
void clasname::swap(char &a,char& b )
{
char temp = b;
b = a;
a = temp;
}


Thanks again for giving me idea of swapping.

jpn
10th January 2008, 08:42
Even if qSwap() doesn't work as expected, it compiles fine for me at least:


QString str("12");
qSwap(str[0], str[1]);
qDebug() << str; // "22"


However, the first method suggested by Wysota works perfectly.


QString str("341256");
QChar* dat = str.data();
qSort(dat, dat + str.length());
qDebug() << str; // "12345"

wysota
10th January 2008, 12:57
However, the first method suggested by Wysota works perfectly.

So this will work as well:

QString str="173562";
QChar *dat = str.data();
qSwap(dat[1], dat[2]);

spud
10th January 2008, 14:26
The following code will in most likely cause your application to crash:
char * str1 = Q_date.toAscii().constData();
swap( str1[0], str1[2] );and even if it doesn't it won't work.
You shouldn't save a pointer to the temporary object returned by toAscii(), it goes out of scope immediately. Go with Wysota's suggestion.

@jpn + wysota: It's an interesting side effect of Qt's trick with QCharRef that swap doesn't work as expected. I think they should mention QCharRef in the documentation and that it's sometimes more efficient(in this case necessary) to work on the raw QChar array returned by data()