0% found this document useful (0 votes)
16 views2 pages

Reverse String

Uploaded by

krishnavaithi36
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Reverse String

Uploaded by

krishnavaithi36
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

public String reverseWords_andCase(String sentence, int case_option) {

// Split the sentence into words based on spaces


String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();

// Process each word in the sentence


for (int i = 0; i < words.length; i++) {
String originalWord = words[i];
String reversedWord = reverseWord(originalWord);

// Modify the word based on the case_option


String modifiedWord;
if (case_option == 0) { // Normal reversal
modifiedWord = reversedWord;
} else if (case_option == 1) { // Retain case positions
modifiedWord = retainCasePositions(originalWord, reversedWord);
} else {
throw new UnsupportedOperationException("Invalid case_option: " + case_option);
}

// Append the modified word to the result


result.append(modifiedWord);

// Add a space if it's not the last word


if (i < words.length - 1) {
result.append(" ");
}
}

// Assign the result to the output variable


output1 = result.toString();
return output1; // Return the final reversed string
}

// Helper function to reverse a word


private String reverseWord(String word) {
return new StringBuilder(word).reverse().toString();
}

// Helper function to retain original case positions


private String retainCasePositions(String original, String reversed) {
char[] result = reversed.toCharArray();
for (int i = 0; i < original.length(); i++) {
if (Character.isUpperCase(original.charAt(i))) {
result[i] = Character.toUpperCase(result[i]);
} else if (Character.isLowerCase(original.charAt(i))) {
result[i] = Character.toLowerCase(result[i]);
}
}
return new String(result);
}

You might also like