Reputation: 73
I have a Text Which is being encoded using base64 For example I have a String
string = "Hello"
It is encoded
Encoded string is :"SGVsbG9XQ1Q="
and then prepend the string with "||" (2-Pipe Character)
Now problem is I want to replace all =
in that encoded string with |
(one pipe) only at end of strings not in middle of any string
How will I replace all =
only at end of the String with |
in qt c++?
Here is my code:
#include <QCoreApplication>
#include <QString>
#include <QDebug>
#include <QByteArray>
QString base64_encode(QString string);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString srcString = "HelloWCT";
QString encodedString = base64_encode(srcString);
qDebug() << "Encoded string is" << encodedString;
return a.exec();
}
QString base64_encode(QString string){
QByteArray ba;
ba = ba.append(string);
ba = ba.toBase64();
ba = ba.prepend("||");
return(ba);
}
How to apply my replacing logic only at end of string?can anybody help me with the logic?
I have logic but dont know how to apply it?
Logic is: it will start checking from end of string if there is "=" it will replace it with "|" and it wil gain check if there exist another "=" before the last equal to it will again replace and then if before second "=" if there is another character it will stop replacing how can we do this ?
Upvotes: 0
Views: 84
Reputation: 8355
You can loop through the QByteArray
from the end to the beginning (and break the loop when you find a character other than '='
), replacing every occurrence of '='
by a '|'
, something like this:
QByteArray ba("SGVsbG9XQ1Q=");
for(int i=ba.length()-1; i>=0 && ba[i]=='='; i--)
ba[i] = '|';
Upvotes: 1
Reputation: 73
I have found the exact solution:
for(int i=ba.length()-1; i>=0 ;i--)
if(ba.at(i) == '=')
{
//replace with "|"
ba.replace(i,1,QByteArray("|"));
}
else
break;
Upvotes: 0