Reverse a given string without using the library.
Example 1:
Input: str="Hello Word"
Output: droW olleH
Approach:
Java
public class ReverseString {public static void main(String[] args) {String str = "Hello Word";String strRev = reverseString(str);System.out.println("Reverse string is: " + strRev);System.out.println("Reverse string is: "+ reverseStringChar(str));}public static String reverseString(String str) {// create new string for hold the resultStringBuffer strBuff = new StringBuffer();for (int i = str.length() - 1; i >= 0; i--) {strBuff.append(str.charAt(i));}return strBuff.toString();}public static String reverseStringChar(String str) {// create new string for hold the resultStringBuffer strBuff = new StringBuffer();char array[] = str.toCharArray();for (int i = array.length - 1; i >= 0; i--) {strBuff.append(Character.toString(array[i]));}return strBuff.toString();}}
C++
#include <bits/stdc++.h>using namespace std;//function to reverse the stringstring stringReverse(string str){//vaiable to hold the final//answerstring rev="";//iterate till the length//of stringfor(int i=0;i<str.size();i++){//rev=str[i]+rev//append in reverse orderrev=str[i]+rev;}return rev;}int main(){string str="Hello Word";string rev=stringReverse(str);cout<<"Reverse string is\n";cout<<rev<<"\n";return 0;}
No comments:
Post a Comment