Quick actions

cmd+k|ctrl+k

Navigation

Languages

Reverse a String

Snippet info

Language

Java

Visibility

public

Author

shraddharao-

Created

2024-02-27T08:38:39.536093Z

Updated

2024-02-27T08:38:40.869685Z

class Main {
    /*
    Write a function or program that takes a string as input and returns the string reversed.
    input="Hello, World!"
    output ="!dlroW ,olleH"
    */
    
    // first convert the str into charArray
    // two pointers --> one will be the start poition and other one in the end
    //start swapping at the position pointed by the two pointers
    // increment the starter pointer and decrement the end pointer
    // return the reversed string
    
    public static String reverseString(String str){
        char[] charArray = str.toCharArray();
        int start = 0;
        int end = str.length() - 1;
        
        // while loop swapping
        while(start<end){
            char temp = charArray[start];
            charArray[end] = charArray[start];
            charArray[end] = temp;
            start++;
            end--;
        }
        return new String(charArray);
    }
    
    
 
    public static void main(String[] args) {
     String input = "Hello, World!";
     String isReversed = reverseString(input);
        System.out.println(isReversed);
    }
}
INFO