求助:实现反转字符串中每第n个单词(禁用String.re相关方法)
Hey there! No worries at all—first questions are totally welcome here, don't hesitate to ask anything 😊 Let's work through this problem together, since you already know how to reverse an entire string, we can build on that to target every nth word instead.
Before jumping into the logic, we need to lock down input validity to avoid weird errors later:
- Check if the input
nis a positive integer (no zeros, negatives, or non-numeric values allowed) - Verify the input string has at least one actual word (empty strings or strings with only spaces don't count)
- If
nis larger than the total number of words in the string, alert the user—there's no nth word to reverse in that case
First, split your input string into a list of individual words. Most languages have built-in methods to handle this cleanly (like Python's split() which automatically ignores extra spaces between words, so you don't have to worry about messy input formatting).
Since you can't use String.reverse() or similar, let's craft our own function to flip a single word. For example, in Python:
def reverse_word(word): reversed_str = "" for char in word: # Add each character to the front of the result string to reverse it reversed_str = char + reversed_str return reversed_str
This works by iterating through each character in the word and prepending it to a new string—simple, manual, and avoids any off-limits built-in functions.
Now, loop through your list of words. Remember: we're targeting every nth word (1st, nth, 2nth, 3nth...). Since most languages use 0-indexed lists, we'll check if (index + 1) % n == 0—this tells us when we're at an nth word (e.g., index 1 is the 2nd word, so (1+1)%2=0 triggers the reversal).
For each matching word, replace it with the reversed version using our custom function.
Once all targeted words are reversed, join the list of words back together with spaces to get your final output string.
Here's a complete script putting all these steps together:
def reverse_word(word): reversed_str = "" for char in word: reversed_str = char + reversed_str return reversed_str def reverse_nth_words(input_str, n): # Input validation checks if not isinstance(n, int) or n <= 0: return "Error: Please enter a positive integer for n." words = input_str.strip().split() if not words: return "Error: Please enter a non-empty string with at least one word." if n > len(words): return f"Error: n ({n}) is larger than the number of words ({len(words)}) in the string." # Process each word to reverse every nth one for i in range(len(words)): if (i + 1) % n == 0: words[i] = reverse_word(words[i]) # Join back into a single string return ' '.join(words) # Test the function with user input user_str = input("Enter a string: ") try: user_n = int(input("Enter n (positive integer): ")) print(reverse_nth_words(user_str, user_n)) except ValueError: print("Error: n must be an integer.")
- The
try-exceptblock catches cases where the user enters a non-integer value forn(like a string or decimal) strip()removes leading/trailing spaces from the input string before splitting, keeping our word list clean- The custom
reverse_wordfunction works for any word length, no matter how short or long
Hope this helps you nail exactly what you need—feel free to ask if you need adjustments for a specific programming language!
内容的提问来源于stack exchange,提问作者Dev_elop_er_

