After-school practice

Source: Internet
Author: User
Tags character classes

1, multiple ways to determine the number of occurrences of the character ' I ' in the string "Mingrikejijavabu"

 PackageCom.hanqi; Public classNumber { Public Static voidMain (string[] args) {String num=NewString ("Mingrikejijavabu"); System.out.println ("Original string:" +num); //The first of these methods              intB=0;  for(intA=0;a<num.length (); a++)       {           if(Num.charat (a) = = ' I ') {b++; }} System.out.println ("Number of occurrences of the first method I:" +b); //The second method ofstring[] Str=Newstring[]{"M", "I", "N", "G", "R", "I", "K", "E", "J", "I", "J", "a", "V", "a", "B", "U"}; intSum=0; System.out.print ("Raw Data:");  for(String t:str) {System.out.print (t); } System.out.println ("");  for(inta=0;a<str.length;a++)          {              if(str[a]== "I") {sum+=1; }} System.out.println ("Number of times the second method I appears:" +sum); }}
to determine the number of occurrences of a character in a string

2. Remove spaces with For loop and if loop statements

 PackageCom.hanqi; Public classZuoye1 { Public Static voidMain (string[] args) {String str=NewString ("Zhang San Harry"); System.out.println ("Original string:" +str); System.out.println ("Original string length:" +str.length ()); intM=0; Char[] str1=New Char[Str.length ()-m];  for(intI=0;i<str.length (); i++)    {        if(Str.charat (i)! = ")        {             for(intj=i;j<=i;j++) {str1[j-m]=Str.charat (i); }        }        Else        {             for(intj=i;j<=i;j++) {m++; }}} String str2=NewString (STR1); //System.out.println ("m=" +m);System.out.println ("Remove space after string:" +str2.substring (0, Str.length ()-m)); System.out.println ("String length after Processing:" +str2.substring (0, Str.length ()-m). Length ()); }}
remove spaces with for loop and if loop statements

3, a variety of methods to implement the string "I am Chinese, I am Shandong" is the "Shandong people" end

 PackageCom.hanqi; Public classZuoye { Public Static voidMain (string[] args) {String str=NewString ("I am a Chinese, I am a shandong person"); System.out.println ("Original string:" +str); //The first of these methodsSystem.out.println ("The first method outputs the result:" +str.endswith ("Shandong People")); //The second method ofSystem.out.println ("The second method outputs the result:" + (Str.indexof ("Shandong People") ==str.length ()-3)); //The third method ofSystem.out.println ("The third method outputs the result:" + (Str.charat (Str.length ()-3) = = ' Mountain ' &&Str.charat (str.length ()-2) = = ' East ' && Str.charat (Str.length ()-1) = = ' People ')); //Fourth MethodSystem.out.println ("The fourth method outputs the result:" + (Str.substring (Str.length () -3, Str.length ())). Equals ("Shandong people")); }}
multiple methods to determine the ending character

4. Regular expressions

Regular Expressions (Regular Expressions) are not Java patents, many languages like Perl,python,php,ruby and so on support regular expressions, regular expressions are the weapon of string processing, it is a formula to describe the string pattern, The core value of a regular expression is to match a string. The regular expression engines implemented in each language are not exactly the same, and the oreilly published "Mastering Regular Expressions" is a classic tutorial on regular expressions. This is just a summary of the relevant knowledge of regular expressions in Java, The regular expression functionality in Java is implemented through the two classes in the Java.util.regex package: The pattern class, which defines the object that encapsulates the regular expression, and the Matcher class, which defines the object that encapsulates a state machine that can use a given pattern object to search for a specific String. The Patternsyntaxexception class is also defined in this package and throws an exception if a syntax error is found when compiling a regular expression to create a pattern object. The regular expression is also a string, it is generally encapsulated into a pattern object, in some simple case, can be completely without the regex package, only the String class matches () can be used to determine whether the string and regular expression matching. For example:

"One Piece". Matches ("one.*");//true

Using the regular formula in Java is basically simple:

(1) A string containing a regular expression is passed to the static method of the Pattern class compile () to create a pattern object.

(2) Then by calling the Matcher () method of the Pattern object and taking the string to be searched as an argument to obtain a Matcher object.

(3) Call the Find () method of the Matcher object to search for a string.

(4) If the pattern string is found, you can query the Matcher object to find out where the pattern string is located in and what other information it matches.

The above 4 steps are "JAVA2 primer"---Ivor Horton this book, These steps show us how to learn the regular expression: 1. The most important thing is to write regular expressions, that is, to master the regular expression syntax to write the pattern of the string you want to match, such as to match an email address, how to write a regular formula. 2. Understand Matcher (), find (), compile () and other methods of the role, in fact, is to check the API, see the parameters of these methods, the return value is what, the role of what. 3. The programming of regular expressions is done according to certain steps, as required. Now the learning routine is very clear, simply said: Master Grammar----understand the method--follow the steps.

The following first step, the Java normal expression syntax, here is the context of clear grammar, the specific syntax are donuts, because Baidu, wiki and other search engines can directly search for the regular grammar of the detailed explanation. The syntax elements of a regular expression are the following: regular characters, character classes (character sets), wildcard characters, quantifiers, boundary matches, operators, groups, and flag sequences. Combine examples to help impartiality and the context of the expression syntax.

For example, there is a string "0310handan", we have to write a regular formula to describe the string, the simplest way to do it? Just write 0310handan (check API will see the method compile argument is a string regex, the regular expression is given as a string, but in itself is not a string, here in order to highlight the syntax of regular expressions, so do not have the quotation marks), This is the use of regular characters, and regular characters are matched by their literal meanings. To do all this. The regular expression is one by one mapped, a string corresponding to a regular expression, we say that the regular expression is a weapon to describe the string, which means that two points: 1. A regular expression can describe multiple or even infinite strings, which reflects its powerful description. 2. A string can be represented as multiple regular expressions, which reflects its flexibility. Because it is both powerful and flexible, it is called a "sharp weapon." The next syntax feature is to serve these two points. Matching process is a character in the match, such as "0310handan", written as a regular expression is 10 unit items, in turn corresponds to 0,3,1,0,h,a,n,d,a,n, adding what grammatical characteristics can let a regular formula in a unit to match a lot of characters, The natural idea is to use a unit item to represent a set of characters that have a certain commonality, called a character class, such as [XYZ] can match x, Y or z,[^xyz] to any character other than x, Y, [A-z] matches all lowercase letters, and \d can match the number 0-9. Wait a minute. Java Regular Expression API provides a rich set of predefined character classes to express this idea, commonly used in the following, \d,\d,\w,\w,\s,\s. These are pretty good memories, because they're too common. So notation is simple, Java also provides a large number of character classes with the following general form, \p{name},name specifies the name of the class, here are a few examples:

\p{lower} contains lowercase letters

\p{upper} contains uppercase letters

\P{PUNCT} contains all the punctuation

Regardless of notation, these all represent a unit item that matches a character, and also misses a "big shot", which is a wildcard, written out to be a dot ".", why is it a big shot, it can match all the characters.

Here Although the long experience, but there are doubts, the ability to express is strong, but it is still very troublesome to write, to "0310handan" for example, or to write out 10 units, but each unit has a variety of options can be written, such as can write ... \d.....\p{ Lower}, but it is not written out is longer, can not help but sigh this is the expression of white learning, good trouble. In this paper, we introduce a simple grammatical characteristic of regular expression, that is, quantifier, which is divided into greedy quantifier, coercive quantifier, and possessive word. Quantifier is very useful and easy to use, it determines how many times a unit item will be matched, and simply can combine multiple identical units, so the above notation is syntactically capable of matching "0310handan", which is impossible to do in practice, because to try to represent each character as a uniform form, Then use a quantifier can be written concise, for example, with this formula to match the string: \d\d\d\d\w\w\w\w\w\w, after the use of quantifiers can be written: \d+\w{6} quantifiers are as follows:

+ match 1 or more times

* Match 0 or more times

? Match 0 or 1 times

These 3 are very common, but as long as these three words are enough? Obviously, this does not specify a specific amount, with {num} can specify the number of times, for example, x{2} matches "xx". Now enough, the number of fixed times is not flexible enough, but also to specify the minimum number of times and the maximum number of {Min,max}, here does not specify Max also can, for example, X{2,} can match "xx", "xxx", "xxxx", and so on. The type of quantifiers now seems to suffice. In fact, not finished, so far to talk about is greedy quantifier, then the coercion of quantifiers and the share of the word is what? Explain later.

After-school practice

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.