Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

c++ - How can I create an "isalnum" equivalent?

I was wondering if I am writing correct "isalnum" logic. This program is checking if the string is a palindrome or not and when I input the string "race a car", it keeps saying it is true, i.e. it's a palindrome.

bool isPalindrome(string s) {
  for (int i = 0, j = s.size() - 1; i < j; i++, j--) {
    while ((s[i] < 'a' || s[i] > 'z') && (i < j) ||
           (s[i] < 'A' || s[i] > 'Z') && (i < j) ||
           (s[i] < '0' || s[i] > '9') && (i < j))
      i++;
    while ((s[j] < 'a' || s[j] > 'z') && (i < j) ||
           (s[j] < 'A' || s[j] > 'Z') && (i < j) ||
           (s[j] < '0' || s[j] > '9') && (i < j))
      j--;
    if (toupper(s[i]) != toupper(s[j])) return false;
  }
  return true;
}
question from:https://stackoverflow.com/questions/65601050/how-can-i-create-an-isalnum-equivalent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, your logic is not correct, well, at least not for all the character sets that C++ can use. In ASCII, the letters of the alphabet are in contiguous blocks, so something like

(s[i]<'A'||s[i]>'Z')

works just fine. The issue with that is that ASCII isn't the only character set C++ supports. The most common example to counterpoint ASCII is EBCDIC which has the characters {, }, and in between A and Z.


One thing that is guaranteed though is that 0 through 9 are contiguous in all character sets that C++ supports so it's always legal to text if a character is a number using

if (char_var >= '0' && char_var <= '9')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...