Wednesday, 25 October 2023

JAVA

Reversing the given string

We are going to develop a function that will reverse the given
string while preserving the positions of capital letters and 
punctuation marks and spaces
For example --- 

Input :

MINtech is the best

Output :

tsebeht si hce tNIM

Lets get started

 
      
  1. /* now we are going to create a function that will
  2. reverse the given string whithout touching the
  3. positions of capital letters . and punctuation marks */
  4. import java.util.* ;
  5. public class MINtech{
  6. // Define a static method named "MINtechJAVA" which takes a string as input
  7. public static String MINtechJAVA(String str){
  8. // Convert the input string to a character array
  9. char[] arr = str.toCharArray() ;
  10. // Initialize two pointers, "left" and "right", to reverse the string
  11. int left = 0 ;
  12. int right = arr.length -1 ;
  13. // Start a loop that continues until "left" is less than "right"
  14. while(left < right){
  15. // Move the "left" pointer to the right while it's not a letter
  16. while(left < right && !Character.isLetter(arr[left])){
  17. left++ ;
  18. }
  19. // Move the "right" pointer to the left while it's not a letter
  20. while(left < right && !Character.isLetter(arr[right])){
  21. right -- ;
  22. }
  23. // Swap the characters at the "left" and "right" positions
  24. char temp = arr[left] ;
  25. arr[left] = arr[right] ;
  26. arr[right] = temp ;
  27. // Move the pointers inward
  28. right -- ;
  29. left ++ ;
  30. }
  31. // Convert the character array back to a string and return it
  32. return new String(arr) ;
  33. }
  34. // Main method to execute the program
  35. public static void main(String[] args) {
  36. // Create a Scanner object to read user input
  37. Scanner sc = new Scanner(System.in);
  38. System.out.println("Enter a string that you want to reverse : ");
  39. // Read a line of input from the user
  40. String str = sc.nextLine();
  41. // Call the "MINtechJAVA" function and print the reversed string
  42. System.out.println(MINtechJAVA(str));
  43. }
  44. }

Output

      Enter a string that you want to reverse : 
      MINtech is amzing
      gnizmas ih cetNIM

      Enter a string that you want to reverse : 
      I Love MINtech
      h cetN IMevoLI

  https://www.toprevenuegate.com/rzm38ght?key=d841e7a69b77ba94bcb8e38c0573aab0
        
https://www.toprevenuegate.com/rzm38ght?key=d841e7a69b77ba94bcb8e38c0573aab0 https://www.toprevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796
https://www.toprevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796
https://www.toprevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796
https://www.toprevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796
https://www.toprevenuegate.com/s4ttwmua2u?key=c02c9252219c2ddb8d72b452016a4796

No comments:

Post a Comment