Ir daudz veidu, kā apgriezt virkni Java. Mēs varam apgriezt virkni, izmantojot StringBuffer, StringBuilder, iterāciju utt. Apskatīsim veidus, kā apgriezt virkni Java.
1) Izmantojot StringBuilder / StringBuffer
Fails: StringFormatter.java
public class StringFormatter { public static String reverseString(String str){ StringBuilder sb=new StringBuilder(str); sb.reverse(); return sb.toString(); } }
Fails: TestStringFormatter.java
public class TestStringFormatter { public static void main(String[] args) { System.out.println(StringFormatter.reverseString('my name is khan')); System.out.println(StringFormatter.reverseString('I am sonoo jaiswal')); } }
Izvade:
nahk si eman ym lawsiaj oonos ma I
2) Ar apgriezto iterāciju
Fails: StringFormatter.java
public class StringFormatter { public static String reverseString(String str){ char ch[]=str.toCharArray(); String rev=''; for(int i=ch.length-1;i>=0;i--){ rev+=ch[i]; } return rev; } }
Fails: TestStringFormatter.java
public class TestStringFormatter { public static void main(String[] args) { System.out.println(StringFormatter.reverseString('my name is khan')); System.out.println(StringFormatter.reverseString('I am sonoo jaiswal')); } }
Izvade:
nahk si eman ym lawsiaj oonos ma I