Site icon Ninotronix

Reverse a String – Using Python , Java , C

Using Python

def reverse_string(s):
    return s[::-1]

input_string = "hello"
reversed_string = reverse_string(input_string)
print(reversed_string)

Using Java

public class StringReversal {
    public static String reverseString(String s) {
        char[] chars = s.toCharArray();
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        String inputString = "hello";
        String reversedString = reverseString(inputString);
        System.out.println(reversedString);
    }
}

Using C

#include <stdio.h>
#include <string.h>

void reverseString(char* s) {
    int length = strlen(s);
    for (int i = 0; i < length / 2; i++) {
        char temp = s[i];
        s[i] = s[length - i - 1];
        s[length - i - 1] = temp;
    }
}

int main() {
    char inputString[] = "hello";
    reverseString(inputString);
    printf("%s\n", inputString);
    return 0;
}

Exit mobile version