В этом сообщении блога мы рассмотрим, как перевернуть строку, содержащую специальные символы, с помощью Python и JavaScript. Мы пошагово объясним код и приведем примеры для демонстрации функциональности. Давайте погрузимся!
Реализация JavaScript:
// This function takes an input string and reverses it while preserving the position // of special characters. Special characters are defined as any characters that are // not letters (A-Z or a-z) or digits (0-9). function reverseStringWithSpecialChars(inputStr) { // Step 1: Find all the special characters in the input string and store them in 'specialChars'. const specialChars = inputStr.match(/[^A-Za-z0-9]/g); // Step 2: Remove all special characters from the input string, reverse the remaining alphanumeric // characters, and store the result in 'reversedAlphaNumeric'. const reversedAlphaNumeric = inputStr.replace(/[^A-Za-z0-9]/g, '').split('').reverse().join(''); // Initialize an empty string 'reversedStr' to store the final reversed string. let reversedStr = ''; // Initialize a variable 'specialCharIndex' to keep track of the special characters. let specialCharIndex = 0; // Step 3: Loop through the original input string. // Loop through each character in the input string. for (let i = 0; i < inputStr.length; i++) { // Check if the current character is a special character: if (/[^A-Za-z0-9]/.test(inputStr[i])) { // If it's special: // - Take the next special character from 'specialChars'. // - Add that special character to the result string ('reversedStr'). // - Move to the next special character by increasing 'specialCharIndex'. reversedStr += specialChars[specialCharIndex]; specialCharIndex++; } else { // If it's not special (i.e., it's a letter or digit): // - Take the corresponding character from the reversed alphanumeric string ('reversedAlphaNumeric'). // - Add that character to the result string ('reversedStr'). // - To ensure the characters align correctly, we use 'i - specialCharIndex' to adjust the index. reversedStr += reversedAlphaNumeric.charAt(i - specialCharIndex); } } // Step 4: Return the final reversed string with special characters in their original positions. return reversedStr; } // Example usage: const inputStr = "th-gfE-dCbal"; const result = reverseStringWithSpecialChars(inputStr); console.log(result); // Output: "la-bCd-Efght"
Реализация Python:
def reverse_string_with_special_chars(input_str): # Step 1: Find all special characters and store them in 'special_chars'. special_chars = ''.join([char for char in input_str if not char.isalnum()]) # Step 2: Reverse the alphanumeric characters and store them in 'reversed_alphanumeric'. reversed_alphanumeric = ''.join([char for char in input_str if char.isalnum()])[::-1] # Initialize an empty string 'reversed_str' to store the final reversed string. reversed_str = '' # Initialize a variable 'special_char_index' to keep track of special characters. special_char_index = 0 # Step 3: Loop through the input string. for i in range(len(input_str)): # If the current character is not alphanumeric (a special character): if not input_str[i].isalnum(): # Add the next special character from 'special_chars' to 'reversed_str'. reversed_str += special_chars[special_char_index] # Move to the next special character. special_char_index += 1 else: # If the current character is alphanumeric: # Add the corresponding character from 'reversed_alphanumeric' to 'reversed_str'. # Adjust the index by subtracting 'special_char_index' to account for special characters. reversed_str += reversed_alphanumeric[i - special_char_index] # Step 4: Return the final reversed string with special characters in their original positions. return reversed_str # Example usage: input_str = "th-gfE-dCbal" result = reverse_string_with_special_chars(input_str) print(result) # Output: "la-bCd-Efght"
Изучая больше алгоритмов и концепций, помните, что практика и настойчивость имеют решающее значение. Чем больше вы будете решать проблемы и совершенствовать свои навыки, тем увереннее и способнее вы станете как программист. Итак, продолжайте программировать, продолжайте исследовать и продолжать решать новые задачи. Приятного кодирования!
Примечание::
👋Привет! Если у вас есть острые вопросы или вы просто хотите поздороваться, не стесняйтесь — я на расстоянии всего лишь сообщения. 💬 Вы можете связаться со мной по адресу [email protected].
🤝 Кстати, я думаю, у нас одинаковый интерес к разработке программного обеспечения — давайте подключимся к LinkedIn! 💻