Reversing a String with Special Characters: A JavaScript and Python Journey
In this blog post, we will explore how to reverse a string containing special characters using both Python and JavaScript. We will walk through a step-by-step explanation of the code and provide examples to demonstrate the functionality. Let’s dive in!
JavaScript Implementation:
// 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 Implementation:
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"
Or,
def reverse_string_with_special_characters(s):
# Convert string to list for easier manipulation
s = list(s)
# Initialize pointers for start and end of the string
left, right = 0, len(s) - 1
# Loop until pointers meet
while left < right:
# Check if characters at pointers are not alphabetic
if not s[left].isalpha():
left += 1
elif not s[right].isalpha():
right -= 1
else:
# Swap alphabetic characters
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# Convert list back to string
return ''.join(s)
# Example usage
input_string = "th-gfE-dCbal"
reversed_string = reverse_string_with_special_characters(input_string)
print("Reversed string with special characters:", reversed_string)
As you explore more algorithms and concepts, remember that practice and persistence are key. The more you tackle problems and refine your skills, the more confident and capable you’ll become as a programmer. So, keep coding, keep exploring, and keep embracing new challenges. Happy coding!
Note::
👋 Hey there! If you have any burning questions or just want to say hi, don’t be shy — I’m only a message away. 💬 You can reach me at jamilkashem@zoho.com.
🤝 By the way, I think we share the same interest in software engineering — let’s connect on LinkedIn! 💻