Write a program to reverse a string
Example 1:
Input: char={'a','g','p','d'}
Output: reverse ={'d','p','g','a'}
Approach:
Java
public class ReverseCharArrayString {public static void main(String[] args) {char str[] = { 'a', 'g', 'p', 'd' };reverseString(str);System.out.println(str);}public static void reverseString(char[] s) {// length of given char arrayint n = s.length;// iterate till n/2for (int i = 0; i < n / 2; i++) {// swap character positionchar tmp = s[i];s[i] = s[n - i - 1];s[n - i - 1] = tmp;}}}
C++
#include <bits/stdc++.h>using namespace std;//function to reverse the character//arrayvoid reverseString(char str[],int n){for(int i=0;i<n/2;i++){//swapping the charater positionchar temp=str[i];str[i]=str[n-i-1];str[n-i-1]=temp;}}int main(){char str[] = { 'a', 'g', 'p', 'd' };int n=sizeof(str)/sizeof(str[0]);reverseString(str,n);for(int i=0;i<n;i++)cout<<str[i]<<" ";return 0;}
No comments:
Post a Comment