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.
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.
You mean you want to sort it or make an arbitrary change?
This might just work:
Qt Code:
qSort(dat, dat+str.length());To copy to clipboard, switch view to plain text mode
If you want arbitrary changes then swap characters manually.
Qt Code:
qSwap(str[2], str[3]);To copy to clipboard, switch view to plain text mode
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:
Qt Code:
classname::function() { .... 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; }To copy to clipboard, switch view to plain text mode
Thanks again for giving me idea of swapping.
Last edited by jpn; 10th January 2008 at 07:19. Reason: missing [code] tags
Even if qSwap() doesn't work as expected, it compiles fine for me at least:
Qt Code:
qSwap(str[0], str[1]); qDebug() << str; // "22"To copy to clipboard, switch view to plain text mode
However, the first method suggested by Wysota works perfectly.
Qt Code:
qSort(dat, dat + str.length()); qDebug() << str; // "12345"To copy to clipboard, switch view to plain text mode
J-P Nurmi
So this will work as well:
Qt Code:
qSwap(dat[1], dat[2]);To copy to clipboard, switch view to plain text mode
The following code will in most likely cause your application to crash:and even if it doesn't it won't work.Qt Code:
char * str1 = Q_date.toAscii().constData(); swap( str1[0], str1[2] );To copy to clipboard, switch view to plain text mode
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()
Bookmarks