This is a very basic interview question, but to be considerate.
First, reverse a string:
The basic idea is to change to a char array, then call the method inside C #, or set two index, traverse from head to tail, and swap.
Method One: Array.reverse (char *). Note that the string will be null or empty at the beginning.
Public Static string ReverseString (string input) { if (String.IsNullOrEmpty (input)) { return input; } Char [] Chararray = input. ToCharArray (); Array.reverse (Chararray); return New String (Chararray); }
Method two: Swap characters.
Public Static stringReverseString1 (stringinput) { if(String.IsNullOrEmpty (input)) {returninput; } Char[] Chararray =input. ToCharArray (); Chartmp; for(inti =0, j = chararray.length-1; I < J; i++, j--) {tmp=Chararray[i]; Chararray[i]=Chararray[j]; CHARARRAY[J]=tmp; } return New string(Chararray); }
Reverse the words in a sentence:
Public Static stringReversewords (stringinput) { if(String.IsNullOrEmpty (input)) {returninput; } string[] splits = input. Split (' '). Select (str=>Str. Trim ()). ToArray (); StringBuilder Output=NewStringBuilder (); for(inti = splits. Length-1; I >=0; i--) {output. Append (Splits[i]); if(I! =0) {output. Append (" "); } } returnoutput. ToString (); }
(C #) Reverses the string, reversing the word in a sentence.