在C语言中处理未知长度的用户输入字符串并按规则拆分
How to Split a String into Two Parts (Handle Odd/Even Lengths)
Got it, let's solve this string splitting problem where we need to handle input strings of any length. The rules are clear:
- If the string length is even, split it exactly in half
- If it's odd, the first part should be one character longer than the second
Python Solution
Here's a clean, concise way to do this in Python—no messy if-else checks needed:
# Get user input (works for any length string) input_str = input("Enter your string: ") str_len = len(input_str) # Calculate the length of the first part: this handles both odd/even cases first_part_len = (str_len + 1) // 2 # Split the string first_part = input_str[:first_part_len] second_part = input_str[first_part_len:] # Output the result print(f"Output: {first_part}{second_part}")
How it works:
The magic is in (str_len + 1) // 2:
- For even lengths (e.g., 8 characters like
OddOrEven):(8 + 1) // 2 = 4, so we split after 4 characters (first part:OddOr, second:Even) - For odd lengths (e.g., 9 characters like
OddAndEven):(9 + 1) // 2 = 5, so first part gets 5 characters (OddAn), second gets 4 (dEven)
JavaScript Solution
If you're working with JavaScript, here's an equivalent approach:
// Get user input const inputStr = prompt("Enter your string:"); const strLen = inputStr.length; // Calculate first part length (using Math.ceil works the same way) const firstPartLen = Math.ceil(strLen / 2); // Split the string const firstPart = inputStr.slice(0, firstPartLen); const secondPart = inputStr.slice(firstPartLen); // Log the result console.log(`Output: ${firstPart}${secondPart}`);
This uses Math.ceil(strLen / 2) to get the same split point—for even lengths it returns exactly half, for odd lengths it rounds up to give the first part an extra character.
内容的提问来源于stack exchange,提问作者ACH
相关产品推荐
相关产品推荐

