如何用C语言判断字符串仅含字母还是含数字?代码排查求助
Let's walk through the issues in your code and fix them so the function works as intended:
1. Logical Condition is Backwards & Flawed
Your if condition is checking for non-alphabetic characters but setting p = 1 (which you note means "only letters") when it finds them—this is completely reversed. On top of that, operator precedence in your condition creates unexpected behavior: && has higher priority than ||, so a > 'Z' && a < 'a' gets evaluated first, but the overall logic still fails to correctly flag non-letters.
The correct check for a non-alphabetic character is:
if (!( (a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z') ))
Or even better, use the standard library's isalpha() function (from <ctype.h>) which handles locale-specific edge cases too.
2. Assignment Logic is Reversed
When you spot a non-alphabetic character, you need to mark the string as invalid (p = 0)—and you can even exit the loop early. There's no need to check the rest of the characters once you've found a non-letter. Your original code was setting p = 1 (valid) for invalid characters, which is the opposite of what you want.
3. Unnecessary Full Loop Iteration
Once you hit a non-alphabetic character, you can immediately return 0 instead of continuing the loop. This makes the function far more efficient, especially for long strings.
4. Bonus: String Safety
Strings in C are null-terminated ('\0'), so passing a size_arr parameter can lead to out-of-bounds access if the actual string length is shorter than size_arr. It's safer to loop until you hit the null terminator.
Fixed Code
Here's the corrected version of your function:
#include <ctype.h> // For isalpha() int CheckingString(char *arr) { int i; // Loop until we hit the null terminator of the string for (i = 0; arr[i] != '\0'; i++) { char a = arr[i]; // Check if the character is NOT alphabetic if (!isalpha((unsigned char)a)) { // Found a non-letter, return 0 immediately return 0; } } // If we made it through the whole string, all are letters return 1; }
Key Changes Explained:
- Renamed the function to
CheckingStringfor readability (fixed the typo) - Removed the
size_arrparameter and loop until'\0'to avoid out-of-bounds errors - Used
isalpha()(cast tounsigned charto avoid undefined behavior for characters with negative values) to check for alphabetic characters - Immediately return
0when a non-letter is found, instead of continuing the loop - Return
1only if every character in the string is a letter
If you still want to use the size_arr parameter (for example, if working with fixed-size buffers that aren't null-terminated), here's that version:
#include <ctype.h> int CheckingString(char *arr, int size_arr) { int i; for (i = 0; i < size_arr; i++) { char a = arr[i]; // If we hit the null terminator early, stop checking if (a == '\0') break; if (!isalpha((unsigned char)a)) { return 0; } } return 1; }
内容的提问来源于stack exchange,提问作者Eldadtsabari

