——-Android Training, Java training, look forward to communicating with you! ———-
/*
Reverses a string. Reverses the specified part of the string, "ABCDEFG"; ABFEDCG
Analysis function:
1 The result of a function that reverses the specified string —————— – The return value is of type string.
2 There is no unknown variable – The specified string, the starting bit, and the end bit. – The parameter type is (String str,int start,int end)
Idea: Because you want to specify a part of the string to be reversed, you need to use the foot tag, and then use the array, so the idea is as follows.
1 Convert all strings to character array –char[] ToCharArray ()
2 Invert an array-specified element ———-customize a function reversal array reverse ()
3 Convert all character arrays to strings – constructor method string new (char[] ch). Or a static method of the Statics String copyvalueof (char[] ch);
4 passes the portion of the specified reversal as a parameter.
Array Inversion review:
Sets the head and tail pointer, the head pointer is smaller than the tail pointer when the end of the exchange, the end pointer self-increment and the tail pointer self-subtraction.
A three-variable method is used to exchange operations.
Summary: The function should be as far as possible subdivision, encapsulation, not all put a heap, this is the abstract design idea, so later change will be very convenient.
Note: Features are included with the head does not contain the tail!!
*/
Class Stringreversedemo { Public Static void Main(string[] args) {//target stringString str1 ="Abcdefghijk";//Invert all stringsString str2 = reversestring (STR1); System. out. println (STR2);//Invert the specified stringString STR3 = reversestring (str1,0,3);//Note: Contains header does not contain tailSystem. out. println (STR3); }//Invert the specified string Public StaticStringreversestring(String str,intStart,intEnd) {//1 string to character array Char[] Chararray = Str.tochararray ();//2 specifying array element inversionReversearray (Chararray,start,end);//3 Array to string return NewString (Chararray); }//Invert all strings Public StaticStringreversestring(String str) {returnReverseString (str,0, Str.length ()); }//Specify array element inversion Public Static void Reversearray(Char[] Chararray,intXintY) {//Set up a tail pointer intstart = X,end = y1;//When the head pointer is less than the tail pointer, the end swap while(start<end) swap (chararray,start++,end--); }//array inversion all Public Static void Reversearray(Char[] chararray) {Reversearray (Chararray,0, chararray.length); }//Array specify position swap operation Public Static void Swap(Char[] ch,intXintY) {//Set a temporary variable, three variable method Chartemp = ch[x]; CH[X] = Ch[y]; Ch[y] = temp; }}
Dark Horse Programmer _ Diary 23_ string inversion exercise