logo

Obráťte reťazec v jazyku Java

Tento článok popisuje rôzne spôsoby zvrátenia reťazca v jazyku Java s príkladmi.

Príklady:

string-reverse



Prerequisite:  String vs StringBuilder vs StringBuffer in Java>

Nasleduje niekoľko zaujímavých faktov o triedach String a StringBuilder:

  1. Objekty String sú nemenné.
  2. Trieda String v jazyku Java nemá metódu reverse(), avšak trieda StringBuilder má zabudovanú metódu reverse().
  3. Trieda StringBuilder nemá metódu toCharArray(), zatiaľ čo trieda String má metódu toCharArray().
1. The idea is to traverse the length of the string  2. Extract each character while traversing  3. Add each character in front of the existing string>

Implementácia:

Java




// java program to reverse a word> import> java.io.*;> import> java.util.Scanner;> class> GFG {> >public> static> void> main (String[] args) {> > >String str=>'Geeks'>, nstr=>''>;> >char> ch;> > >System.out.print(>'Original word: '>);> >System.out.println(>'Geeks'>);>//Example word> > >for> (>int> i=>0>; i { ch= str.charAt(i); //extracts each character nstr= ch+nstr; //adds each character in front of the existing string } System.out.println('Reversed word: '+ nstr); } } //Contributed by Tiyasa>

>

>

Výkon

Original word: Geeks Reversed word: skeeG>

Prevod reťazca na bajty: Metóda getBytes() sa používa na konverziu vstupného reťazca na bajty[].

metóda:

1. Create a temporary byte[] of length equal   to the length of the input string. 2. Store the bytes (which we get by using   getBytes() method) in reverse order into   the temporary byte[] . 3. Create a new String abject using byte[] to  store result.>

Implementácia:

Java




// Java program to ReverseString using ByteArray.> import> java.lang.*;> import> java.io.*;> import> java.util.*;> // Class of ReverseString> class> ReverseString {> >public> static> void> main(String[] args)> >{> >String input =>'techcodeview.com'>;> >// getBytes() method to convert string> >// into bytes[].> >byte>[] strAsByteArray = input.getBytes();> >byte>[] result =>new> byte>[strAsByteArray.length];> >// Store result in reverse order into the> >// result byte[]> >for> (>int> i =>0>; i result[i] = strAsByteArray[strAsByteArray.length - i - 1]; System.out.println(new String(result)); } }>

c program na porovnávanie reťazcov

>

>

Výkon

skeeGrofskeeG>

Použitie vstavanej metódy reverse() triedy StringBuilder:

Trieda String nemá metódu reverse(), musíme skonvertovať vstupný reťazec na StringBuilder, čo sa dosiahne použitím metódy append StringBuilder. Potom vytlačte znaky obráteného reťazca skenovaním od prvého po posledný index.

Implementácia:

Java


večera vs čas večere



// Java program to ReverseString using StringBuilder> import> java.lang.*;> import> java.io.*;> import> java.util.*;> // Class of ReverseString> class> ReverseString {> >public> static> void> main(String[] args)> >{> >String input =>'Geeks for Geeks'>;> >StringBuilder input1 =>new> StringBuilder();> >// append a string into StringBuilder input1> >input1.append(input);> >// reverse StringBuilder input1> >input1.reverse();> >// print reversed String> >System.out.println(input1);> >}> }>

>

>

Výkon

skeeG rof skeeG>

Konverzia reťazca na pole znakov: Používateľ zadá reťazec, ktorý sa má obrátiť.

metóda:

1. First, convert String to character array  by using the built in Java String class   method toCharArray(). 2. Then, scan the string from end to start,   and print the character one by one.>

Implementácia:

Java




// Java program to Reverse a String by> // converting string to characters one> // by one> import> java.lang.*;> import> java.io.*;> import> java.util.*;> // Class of ReverseString> class> ReverseString {> >public> static> void> main(String[] args)> >{> >String input =>'GeeksForGeeks'>;> >// convert String to character array> >// by using toCharArray> >char>[] try1 = input.toCharArray();> >for> (>int> i = try1.length ->1>; i>=>0>; i--)> >System.out.print(try1[i]);> >}> }>

>

>

Výkon

skeeGroFskeeG>
  • Preveďte vstupný reťazec na pole znakov pomocou funkcie toCharArray(): Preveďte vstupný reťazec na pole znakov pomocou toCharArray() – vstavanej metódy triedy String. Potom naskenujte pole znakov z oboch strán, tj od počiatočného indexu (vľavo), ako aj od posledného indexu (vpravo) súčasne.
1. Set the left index equal to 0 and right   index equal to the length of the string -1. 2. Swap the characters of the start index   scanning with the last index scanning   one by one. After that, increase the left   index by 1 (left++) and decrease the right   by 1 i.e., (right--) to move on to the next   characters in the character array . 3. Continue till left is less than or equal to  the right.>

Implementácia:

Java




// Java program to Reverse a String using swapping> // of variables> import> java.lang.*;> import> java.io.*;> import> java.util.*;> // Class of ReverseString> class> ReverseString {> >public> static> void> main(String[] args)> >{> >String input =>'Geeks For Geeks'>;> >char>[] temparray = input.toCharArray();> >int> left, right =>0>;> >right = temparray.length ->1>;> >for> (left =>0>; left // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } for (char c : temparray) System.out.print(c); System.out.println(); } }>

>

>

Výkon

skeeG roF skeeG>
  • Použitie objektu ArrayList: Skonvertujte vstupný reťazec do poľa znakov pomocou vstavanej metódy toCharArray(). Potom pridajte znaky poľa do objektu ArrayList. Java má tiež zabudovanú metódu reverse() pre triedu Collections. Keďže metóda reverse() triedy Collections berie objekt zoznamu, na zvrátenie zoznamu prejdeme objekt ArrayList, ktorý je typom zoznamu znakov.
1. We copy String contents to an object   of ArrayList. 1. We create a ListIterator object by using   the listIterator() method on the ArrayList   object. 2. ListIterator object is used to iterate over   the list. 3. ListIterator object helps us to iterate   over the reversed list and print it one   by one to the output screen.>

Implementácia:

Java




// Java program to Reverse a String using ListIterator> import> java.lang.*;> import> java.io.*;> import> java.util.*;> // Class of ReverseString> class> ReverseString {> >public> static> void> main(String[] args)> >{> >String input =>'Geeks For Geeks'>;> >char>[] hello = input.toCharArray();> >List trial1 =>new> ArrayList();> >for> (>char> c : hello)> >trial1.add(c);> >Collections.reverse(trial1);> >ListIterator li = trial1.listIterator();> >while> (li.hasNext())> >System.out.print(li.next());> >}> }>

>

>

Výkon

skeeG roF skeeG>

Použitie StringBuffer:

Trieda String nemá metódu reverse(), musíme skonvertovať vstupný reťazec na StringBuffer, čo sa dosiahne použitím reverznej metódy StringBuffer.

Implementácia:

Java




tabuľka v reakcii

// Java program to demonstrate conversion from> // String to StringBuffer and reverse of string> import> java.lang.*;> import> java.io.*;> import> java.util.*;> public> class> Test {> >public> static> void> main(String[] args)> >{> >String str =>'Geeks'>;> >// conversion from String object to StringBuffer> >StringBuffer sbr =>new> StringBuffer(str);> >// To reverse the string> >sbr.reverse();> >System.out.println(sbr);> >}> }>

>

>

Výkon

skeeG>
  • Obrátenie reťazca prevzatím vstupu od používateľa-

Java




/*package whatever //do not write package name here */> import> java.io.*;> import> java.util.Scanner;> class> GFG {> >public> static> void> main (String[] args) {> >Scanner scanner =>new> Scanner(System.in);> >String Str = scanner.nextLine();> >char>[] arr = Str.toCharArray();> > >String rev =>''>;> > >for>(>int> i = Str.length() ->1>; i>=>0>; i--)> >{> >rev = rev + Str.charAt(i);> >}> > >System.out.println(rev);> > >}> }> >

>

>

Výkon

0>

Vo vyššie uvedenom kóde v podstate čítame reťazec od používateľa pred spustením iteračnej slučky na vytvorenie nového, obráteného reťazca. Funkcia charAt triedy String sa používa na získanie každého znaku pôvodného reťazca jednotlivo od konca a operátor + sa používa na ich zreťazenie do nového reťazca.

Použitie zásobníka:

Myšlienka zásobníka je taká, že budeme pristupovať iba k hornému prvku zásobníka, takže obsahuje 2 kroky:

  1. zatlačte všetky znaky v zásobníku.
  2. vyberte všetky znaky zo zásobníka a pridajte ich k dočasnému reťazcu.

Nižšie je uvedená implementácia vyššie uvedeného prístupu.

Java




import> java.util.*;> class> GFG {> >public> static> void> main(String[] args) {> > >String s=>'Geeks For Geeks'>;> > >//initializing a stack of type char> >Stack stack=>new> Stack();> > >for>(>char> c:s.toCharArray())> >{> >//pushing all the characters> >stack.push(c);> >}> > >String temp=>''>;> > >while>(!stack.isEmpty())> >{> >//popping all the chars and appending to temp> >temp+=stack.pop();> >}> > >System.out.println(>'Reversed string is : '>+temp);> > >}> }> //This code is contributed by aeroabrar_31>

>

>

Výkon

Reversed string is : skeeG roF skeeG>

Časová zložitosť: O(N) N je dĺžka reťazca

Pomocný priestor: O(N) pre zásobník

Súvisiaci článok: Rôzne metódy na zvrátenie reťazca v C/C++

bublinové triedenie

Do tohto článku prispeli Pán. Somesh Awasthi .