-2

how to reverse a string without using inbuilt functions not even charAt() ? I was asked this at an interview and cannot find the solution.

I'm sure he didn't mean to use string buffer , he specifically said no inbuilt functions at all, not even CharAt().

the language is java

3 Answers3

1

how to reverse a string without using inbuilt functions not even

By using the algorithm reverse? I'm assuming c++ here.

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;


int main() {
    string s  = "Hallo";

    reverse( s.begin(), s.end() );
    cout << s << endl;
    return 0;
}

Prints "ollaH"

If you're language is JavaScript, it also seems to have a reverse method on arrays...

The OP indicated that he is using java, in that case this item holds the answer you're looking for:

Community
  • 1
  • 1
Werner Erasmus
  • 3,988
  • 17
  • 31
1

you can reverse String via byte Array.

note that if you use another character, you should specify char-set as a parameter of getBytes(String).

Here is my solution >>

public class Main {
    public static void main(String[] args) {
        String string = "String";
        byte[] byteArr = string.getBytes();
        byte[] secondByteArr = new byte[byteArr.length];

        for(int i = 0; i < byteArr.length ; i++){
            secondByteArr[(byteArr.length - 1) - i] = byteArr[i];
        }

        System.out.println(new String(secondByteArr));
    }
}

good luck with that:D

Juneyoung Oh
  • 7,318
  • 16
  • 73
  • 121
0

I guess you can transform it to CharArray and reverse it from top-down for loop

String s = "abcdef";
char c[] = s.toCharArray();

for( int i = c.length -1; i>=0; i--)
    System.out.print(c[i]);
Sayat Satybald
  • 6,300
  • 5
  • 35
  • 52