How to reverse a string in java programming language? without use of any built in function.
Asked
Active
Viewed 79 times
0
-
1Copy the string into a character array, reverse that, make a new String out of it. – Thilo Mar 20 '21 at 07:10
-
1Iterate over the string in the reverse order, read the characters and append them to a new, initially empty string. – Alex Sveshnikov Mar 20 '21 at 07:10
-
3The problem is ill-defined. You **have** to call some built-in functions (methods, actually) to even get to the content of a `String` (for example `toCharArray`). – Joachim Sauer Mar 20 '21 at 07:20
-
This question is meaningful and may be resolved _without_ built-in functions only in languages like good old `C` where a String is a synonym of char array `char[]` or a sequence of char ending with `\0` (ASCIIZ strings) referred by `char*` pointer. – Nowhere Man Mar 20 '21 at 08:30
1 Answers
0
Here is one way you can do it by converting it into a char
array and prepending each element of the array onto an empty string:
public class ReverseString{
public static void main(String[] args){
String str = "abcde";
//make char array
char[] array = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
array[i] = str.charAt(i);
}
//reverse by prepending to a string
String newString = "";
for (char character : array){
newString = character + newString;
}
System.out.println(newString);
}
}

Jamin
- 1,362
- 8
- 22
-
Two _built-in functions_ `length()` and `charAt()` are used here :) And use of intermediate `array` along with the additional loop seems to be redundant. – Nowhere Man Mar 20 '21 at 07:31
-
Could be wrong, but I think the OP may have meant to say only using built in functions. The code is redundant, but I wanted to go with what some other comments were saying about iterating to explain the idea. – Jamin Mar 20 '21 at 07:34