Use strtok() to split the string into words. Now each word uses two pointers, i and j point to the penultimate character and the penultimate character of the string, respectively. Swap these characters, then increase i and decrease j. Repeat these steps when i <j. The following is the implementation of the above method:
str[i] = Character obtained after traversing ascii(str[i]) no. of characters in ‘a-z’ repeatedly after str[i].
Examples:
Input: str = “geeksforgeeks” Output: fbbnddvbfbbnd In the above case str = “geeksforgeeks”, the ASCII value of ‘g’ is 103 therefore ‘g’ has been replaced by moving 103 times from ‘g’ in the desired range i.e., a-z. Hence, character ‘g’ is replaced by ‘f’. Similarly, the complete string “geeksforgeeks” becomes “fbbnddvbfbbnd”. Input: str = “science” Output: dxjbtxb
Approach:
Below is the implementation of above approach:
// Java program for Replace every character of a // string by a different character public class GFG { //Function to manipulate the string static void manipulateString(String str) { char[] str1 = str.toCharArray(); // looping through each character of string for (int i = 0; i < str.length(); i++) { // storing integer ASCII value of // the character in 'asc' int asc = str1[i]; // 'rem' contains coded value which // needs to be rounded to 26 int rem = asc - (26 - (str1[i] - 97)); // converting 'rem' character in range // 0-25 and storing in 'm' int m = rem % 26; // printing character by adding ascii value of 'a' // so that it becomes in the desired range i.e. a-z str1[i] = (char)(m + 'a'); } String str2 = String.valueOf(str1); System.out.println(str2); } //Driver code public static void main(String[] args) { // Declaring str as 'geeksforgeeks' String str = "geeksforgeeks"; manipulateString(str); } }
Output:
fbbnddvbfbbnd