Groovy tip 10 simplified string operations in groovy

Source: Internet
Author: User
Groovy tip 10 simplified string operations in groovyIn groovy, operations on string objects are as convenient as operations on List objects. For example, in Java, the substring method is used for operations on string objects. As follows: String STR = "abcdefg"; system. Out. Println (Str. substring (); the result is: BC has two inconveniences: first, the complexity of the substring method and parameters; second, its last parameter, such as substring) the result is not the first to the third, but the second, of the STR object. This is inconsistent with our intuition and often leads to errors. In groovy, the above Code is transformed into the following: DefSTR = 'abcdefg' PrintlnSTR [1 .. 2] The result is: BC, operate the string object like an array, STR [1 .. 2] what we get is the value from the first to the second, which is in line with our habits. Of course, you can also take any character in the string object: DefSTR = 'abcdefg' PrintlnSTR [, 5]: BDF is great! Since the string object operation is like the list object operation, some methods of the List class such as each can be used directly. DefSTR = 'abcdefg' Str. Each{ PrintIt Print','} Returns a, B, c, d, e, f, g, DefSTR = 'abcdefg' PrintlnStr. Contains ('D') returns true and so on. Other methods, such as "find", "findall", "Every", and "any", can be used in the string object. If you do not like the "FG" character after the STR object and want to delete it from the STR object, you must do this in Java: String STR = "abcdefg "; STR = Str. substring (0, 5); system. Out. Println (STR); In groovy, you can do this: DefSTR = 'abcdefg' STR = str-'fg' PrintlnOf course, you can also subtract "AB" from the STR object: DefSTR = 'abcdefg' STR = str-'AB' PrintlnThe STR result is: cdefg. What if "St" is subtracted from the STR object: DefSTR = 'abcdefg' STR = str-'st' PrintlnThe STR result is abcdefg. What if "be" is subtracted from the STR object: DefSTR = 'abcdefg' STR = str-'Be' PrintlnSTR: abcdefg

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.