-1

How can I check if the last character of value is any letter without comparing it manually with each letter?

   if(value.endsWith("A",Qt::CaseInsensitive)==true)
   ...

This is my code so far, Value has to start with Y/X/Z and have 9 characters

 void Extranjero::setNIE(const QString &value)
{


    if(value.startsWith("Y",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }
    else if(value.startsWith("X",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }
    else if(value.startsWith("Z",Qt::CaseInsensitive)==true && value.length()==9)
    {
    NIE = value;
    }

    else NIE = "Problemon";
}
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Yassin
  • 166
  • 3
  • 8
  • 2
    why not using `std::isalpha`? – TonySalimi Apr 03 '20 at 15:44
  • Does this answer your question? https://stackoverflow.com/questions/8611815/determine-if-char-is-a-num-or-letter it asks for both letters and digits, but the answers should be adjustable easily – 463035818_is_not_an_ai Apr 03 '20 at 15:50
  • Thanks! I didn't know about the isalpha() function – Yassin Apr 03 '20 at 15:55
  • The classic is `if ((c >= 'A') && (c <= 'Z'))`. That covers only uppercase though. – David Schwartz Apr 03 '20 at 16:04
  • @DavidSchwartz -- it may be "classic", but it's wrong. For example, it won't work when the character encoding is EBCDIC. – Pete Becker Apr 03 '20 at 16:35
  • I believe this is much better duplicate candidate since it actually works for QString: https://stackoverflow.com/questions/10231746/how-can-i-find-out-if-a-specific-character-in-a-qstring-is-a-letter-or-punctuati – Dan M. Apr 03 '20 at 17:01

2 Answers2

0

You can use back() and begin() member functions.

if(value.length() == 9){
  QChar tmpChar = value.back();
  if( tmpChar == 'Z' || tmpChar == 'Y' || tmpChar == 'Z'){
   // code..
  }
}
Kor Sar
  • 51
  • 2
  • 4
0

If you want your string to end with any alphabetic character, then you can easily use isalpha. However, in the other case when you want it to start with specific characters like 'X', 'Y' or 'Z', then you need to manually specify them. In order to generalize your code for the latter case, I recommend inserting your specific characters in a set and just check if this set contains the first character of the given string. I hope this helps you solve your problem.

Mohammed Deifallah
  • 1,290
  • 1
  • 10
  • 25
  • Thanks! I didn't know about isalpha() function, now I only need to split my string into a char array to check it. – Yassin Apr 03 '20 at 16:10
  • @Yassin Note that `isalpha` is only suited for regular ascii `char`s. QChar has a [isLetter](https://doc.qt.io/qt-5/qchar.html#isLetter) function that is much better suited. Unless you only need to check against [a-zA-Z]. – Dan M. Apr 03 '20 at 16:58
  • @Yassin If my answer helps you, kindly accept it. – Mohammed Deifallah Apr 03 '20 at 18:32