Java中如何处理字符串大小写?混合大小写字符串升序检测求助
Fixing Mixed-Case String Ascending Order Check in Java
Let's break down the issues with your current code and fix them step by step.
The Core Problem: Case Sensitivity in Character Comparisons
Your code compares characters directly using their raw ASCII values, which causes problems with mixed-case strings. Here's why:
- Lowercase letters (
a-z) have ASCII values from 97 to 122 - Uppercase letters (
A-Z) have ASCII values from 65 to 90
So when you have a string like abcdefgX, the character g (ASCII 103) is actually larger than X (ASCII 88) in raw value comparison—your code will incorrectly mark this as not in order, even though alphabetically g comes before X.
Other Issues in Your Current Code
- The
while (word.equals("END"))blocks are unnecessary and can cause dead loops. A simpleifcheck is enough to exit when "END" is entered. - The
word = word.toString();line is redundant becausewordis already a String object.
Fixed Code with Explanations
Here's the revised code that handles mixed-case strings correctly, plus fixes the other issues:
class Main { public static void main(String args[]) { while (true) { System.out.print("#Enter String: "); String word = BIO.getString(); // Exit immediately if user enters END if (word.equals("END")) { System.exit(0); } boolean inOrder = true; // Convert the entire string to lowercase (or uppercase) to normalize case String normalizedWord = word.toLowerCase(); char previous = normalizedWord.charAt(0); // Start loop from index 1 since we already have the first character as previous for (int j = 1; j < normalizedWord.length() && inOrder; j++) { char current = normalizedWord.charAt(j); // Compare normalized characters instead of raw ASCII values inOrder = current >= previous; previous = current; } if (inOrder) { System.out.println(word + " letters in ascending order"); } else { System.out.println(word + " letters not in ascending order"); } } } }
Key Changes:
- Case Normalization: We convert the input string to lowercase (you could use
toUpperCase()too) before comparing characters. This ensures we're checking alphabetical order regardless of case. - Simplified Exit Logic: Replaced the redundant
whileloops with a singleifcheck for "END"—cleaner and avoids dead loops. - Fixed Loop Index: The for loop starts at
j=1instead ofj=0because we already setpreviousto the first character. Starting at 0 would compare the first character to itself, which is harmless but unnecessary. - Cleaner Output: Used
println()instead ofprint()with\nfor consistent line breaks. - Primitive Boolean: Changed
Boolean inOrdertoboolean inOrder(primitive type is preferred here since we don't need nullability).
How It Works for Mixed-Case Strings
For abcdefgX, normalizedWord becomes abcdefgx. Now when comparing characters:
g(103) is followed byx(120), so120 >= 103is true—your program will correctly mark this as in ascending order.
内容的提问来源于stack exchange,提问作者Josh Gibson
相关产品推荐
相关产品推荐

