What You are About to Learn?
- Array Reversing
- Java String.charAt(index) method
- String Reversing
- StringBuilder
- StringBuffer.reverse() method in Java
- Java String.toCharArray() method
String Reversing Method # 1 :
public class StringReversing {
public static void main(String args[]){
char temp;
String s = new String("Hello");
System.out.println(s);
char str[] = s.toCharArray();
int last = s.length() - 1;
for(int first = 0; first < s.length()/2; first++){
temp = s.charAt(first);
str[first] = str[last];
str[last] = temp;
last--;
}
s = new String(str);
System.out.println(s);
}//end of main
}//end of class
Explanation : In line number 06 i have used the String.toCharArray() method to store the converted(to array of characters) value of the string in Array of characters "str" .
charAt(index) is the build in method in Java String it simply returns the character at the index "index"(index is an integer) it can not be used to assign the value For example i cant do this s.charAt(0) = 'c' . At line #10 the value of first character of the "str" is copied in the variable temp. In 1st iteration of the loop the first char in "str" is replaced by the last and last is replaced by the first one.
Similarly in second iteration of the loop 2nd character is replaced by second last and vice versa. This process will carry on until the whole Array is reversed. And at the end the result is printed in line #18.
String Reversing Method #2 :
public class StringReversing {
2
3 public static void main(String args[]){
4
5 String s = new String("Hello");
6 StringBuffer sb = new StringBuffer(s);
7 System.out.println(s);
8
9 sb.reverse();
10
11 s = new String(sb.toString());
12 System.out.println(s);
13 }//end of main
14
15 }//end of class
Output will be the same.
Explanation : Here i used StringBuffer. I saved the string in the StringBuffer. Then i used the reverse(reverse method is build in for StringBuffer) method for StringBuffer to reverse the it. At the end i copied the saved the converted(to string) value of StringBuffer in the string value and displayed it.
0 comments:
Post a Comment