String space removal and reverse operation example

Source: Internet
Author: User

1. Remove spaces from strings

Package Tan; public class copyofstringtest {public static void main (string [] ARGs) {string S = "Tan at Guigu"; Sop (s); string x = mytrim (s ); sop (x);} public static void Sop (string Str) {system. out. println (STR);} // 1. Remove spaces at both ends of the string. Public static string mytrim (string Str) {int start = 0, end = Str. length ()-1; while (start <= end & Str. charat (start) = '') {start ++;} while (start <= end & Str. charat (end) = '') {end --;} return Str. substring (START, end + 1 );}}

2. Reverse the string

Package Tan; public class stringtest {public static void main (string [] ARGs) {string S = "abcdefgh"; Sop (reversestring (S, 0, 2 )); // indicates reverse Sop (reversestring (s) between 0 and 1;} public static void Sop (string Str) {system. out. println (STR);} // Exercise 2: reverse the string. /** Train of thought: 1. Convert the string into an array. 2. Reverse the array. 3. Convert the array into a string. * // *** Function: [partial inversion] invert the characters between specified badge values * @ Param S * @ Param start * @ Param end * @ return */public static string reversestring (string S, int start, int end) {// string variable array. Char [] CHS = S. tochararray (); // reverse the array. Reverse (CHS, start, end); // convert the array into a string. Return new string (CHS);}/*** function: [reverse all] Reverse the entire string * @ Param S * @ return */public static string reversestring (string S) {return reversestring (S, 0, S. length ();} // end = Y-1; contains the header that does not contain the end. Private Static void reverse (char [] arr, int X, int y) {for (INT start = x, end = Y-1; Start <end; Start ++, end --) {swap (ARR, start, end) ;}} Private Static void swap (char [] arr, int X, int y) {char temp = arr [x]; arr [x] = arr [y]; arr [y] = temp ;}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.