Eliminate whitespace at both ends of a string
1. Determine whether the first position of the string is a space, if it is continued downward judgment, until it is not a space position, the end is the same, forward judgment, until not a space.
2. Gets the string when neither the beginning nor the end is a space.
1 Public Staticstring Mytrim (String str)2 {3 intStart=0,end=str.length ()-1;4 5 while(Start<=end&&str.charat (start) = = ");6start++;7 while(Start<=end&&str.charat (end) = = " );8end--;9 returnStr.substring (start,end+1);Ten}
Flips a string and part of a string
1. String conversions required to flip the ToCharArray () method
2. Flip the array
1 Private Static voidReverseChar[] arr,intXinty)2 {3 for(intstart=x,end=y-1;start<end;start++,end--)4 {5 swap (arr,start,end);6 }7 8 }9 Private Static voidSwapChar[] arr,intXinty)Ten { One Chartemp=Arr[x]; Aarr[x]=Arr[y]; -arr[y]=temp; -}
View Code
3. Converting an array into a string
1 Public Staticstring reversestring (string s)2 {3 //string conversions that need to be flipped array ToCharArray () method4 Char[] CHS =S.tochararray ();5 //flips the array6 reverse (CHS);7 //convert an array to a string8 return NewString (CHS);9}
Flipping part of a string
1 Public StaticString ReverseString (String s,intStartintend)2 {3 //string conversions that need to be flipped array ToCharArray () method4 Char[] CHS =S.tochararray ();5 //flips the array6 reverse (chs,start,end);7 //convert an array to a string8 return NewString (CHS);9 Ten}
View Code
Gets the number of occurrences of a character in another character
1. Define a counter,
2. Get the number of occurrences of the corresponding character
3. Continue to get the occurrence of the corresponding string from the remaining string after the first occurrence, counting once per fetch
4. When get not to be counter statistic complete
1 Lass stringtest_12 {3 Public Static voidMain (string[] args)4 {5String str = "ABKKCDKKEFKKSKK"; 6SOP ("count=" +getsubcount (str, "KK"));7 8 }9 Ten One Public Static intGetsubcount (String str,string key) A { - intCount=0; - intIndex=0; the - while((Index=str.indexof (key))!=-1) - { -SOP ("str=" +str); +str = str.substring (index+key.length ()); -count++; + } A returncount; at } - - Public Static voidSOP (String str) - { - System.out.println (str); - } in}
Java Learning Path Application of--string class method