如何实现字符串大小写互换?含示例及待完善代码
Hey there! Let's work through this string case-swapping problem together. First, I'll share some simple, reliable implementations for common programming languages, then you can drop your existing code (plus any errors or unexpected outputs you're seeing) and we'll troubleshoot it step by step.
Python Solutions
Python has a handy built-in method that does exactly this job—swapcase():
original_string = "Hello World!" swapped_string = original_string.swapcase() print(swapped_string) # Output: hELLO wORLD!
If you want to build the logic manually (great for learning how the underlying process works), here's a custom function that iterates through each character:
def swap_char_cases(input_str): swapped_chars = [] for char in input_str: if char.islower(): swapped_chars.append(char.upper()) elif char.isupper(): swapped_chars.append(char.lower()) else: swapped_chars.append(char) # Leave non-alphabet characters (like ! or spaces) unchanged return ''.join(swapped_chars) # Test the function print(swap_char_cases("Hello World!")) # Output: hELLO wORLD!
JavaScript Solutions
For JavaScript, you can split the string into individual characters, swap each character's case with a map function, then join everything back into a single string:
const originalStr = "Hello World!"; const swappedStr = originalStr.split('').map(char => { if (char === char.toLowerCase()) { return char.toUpperCase(); } else if (char === char.toUpperCase()) { return char.toLowerCase(); } return char; // Keep symbols, numbers, and spaces as they are }).join(''); console.log(swappedStr); // Output: hELLO wORLD!
Share Your Code!
Since you mentioned you've already written code for this, please share these details to help us debug:
- The programming language you're using
- Your full code snippet
- Any error messages you're getting, or the output you're seeing vs. the expected result
That will let us quickly pinpoint exactly what needs fixing.
内容的提问来源于stack exchange,提问作者zinon

