I'm trying to code a function which can ditinguish letters in strings from numerals
and punctuation marks. The problem is that I have used QChar function isLetter and isLetterorNumber(). The compiler gives me no problem but I'm not sure if it will give me any random problems when using it. Could someone tell me if it'll be ok and if not how to make it work ? Also I'm not sure if the last line size = aword.size() is required or if it'll work without it. Thanks.
1 2 3 4 5 6 7 8 9 10 11 12
for (int i = 0, size = aword.size(); i < size; i++)
{
if (aword[i].isLetterOrNumber() && aword[i].isLetter())
{
aword.remove(i--, 1);
size = aword.size();
}
}
if (aword[i].isLetterOrNumber() && aword[i].isLetter())
I think that’s the same as if ( aword[i].isLetter() )
You might be interested in this overloaded QString::remove() method: QString & remove(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive)
It “Removes every occurrence of the character ch in this string”.
Or better in this: QString &QString::remove(const QRegularExpression &re)
“Removes every occurrence of the regular expression re in the string”
I’d take advantage of the last one, mainly because in general I don’t like to change the ‘counter’ variable inside the loop (personal preference).
#include <QApplication>
#include <QLabel>
#include <QLayout>
#include <QRegularExpression>
#include <QString>
#include <QWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget qw;
QString s { "hdfhd OENYAM 023956 ?%&&-#" };
QLabel label(s);
QVBoxLayout layout(&qw);
layout.addWidget(&label);
qw.setLayout(&layout);
qw.show();
auto tmpstr { label.text() + '\n' };
// I prefer an explicit loop if I need to analyze each element:
for (constauto& c : s) {
tmpstr.append( QString("'%1' is a ").arg(c) );
if (c.isLetter() ) {
tmpstr.append("letter\n");
}
elseif (c.isNumber() ) {
tmpstr.append("numeric character");
if(c.isDigit()) {
tmpstr.append(" (a digit)");
}
tmpstr.append('\n');
}
else {
tmpstr.append("weird character of sort\n");
}
}
label.setText(tmpstr);
// I prefer to rely on ready-made algorithms if I can consider elements
// as a 'bunch':
s.remove( QRegularExpression("[A-Za-z0-9]") );
label.setText( QString("%1\n\"%2\"").arg(tmpstr).arg(s) );
return a.exec();
}