File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // Write a java program to reverse the string without using the inbuilt function.
2+
3+ import java .util .Scanner ;
4+
5+ class StringReverse {
6+ public static void main (String [] args )
7+ {
8+ Scanner scan = new Scanner (System .in );
9+ System .out .println ("Enter a String:" );
10+ String str = scan .nextLine ();
11+ System .out .println ("-----------------------" );
12+ System .out .println ("Sting Before Reversing:" );
13+ System .out .println (str );
14+
15+ // Converting the string into character array
16+ char arr1 [] = str .toCharArray ();
17+
18+ // Creating the new array to store the character while reversing
19+ char arr2 [] = new char [arr1 .length ];
20+
21+ // The j value will be used to start storing the character from last index in arr2
22+ int j = arr2 .length - 1 ;
23+
24+ // Using for loop to traverse through the arr1
25+ // In each iteration the character in arr1 is stored in the arr2 from last index in each iteration the j value decrements
26+ for (int i = 0 ; i <= arr1 .length -1 ; i ++) {
27+ arr2 [j ] = arr1 [i ];
28+ j --;
29+ }
30+
31+ // Creating the string using the character array arr2
32+ str = new String (arr2 );
33+ System .out .println ("-----------------------" );
34+ System .out .println ("String After Reversing:" );
35+ System .out .println (str );
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments