S1/using Java to understand program logic/15-strings

Source: Internet
Author: User

To put it simply, the use of strings is mainly divided into two steps.

(1) Define and initialize the string.

(2) Use a string to perform some processing on the string.

You have already learned how to create a string, as shown below.

Create a String Object "Hello World"

String s= "Hello World";

In Java, a string is treated as an object of type string. The string class is a very useful class that is pre-provided by the Java Designer in the Java.lang package, which is automatically imported into all programs by default. The other two ways to create a string object are as shown in the following code.

Create an empty string

String S=new string ();

Or

Create a String Object "Hello World"

String S=new string ("Hello World");

1. The method provided by the string class-the length of the string

Grammar:

String 1.length ();

Returns the length of the string 1.

2. Method provided by the string class--string comparison (including case)

Grammar:

String 1.equals (string 2);

Returns a Boolean value that compares whether the value of two strings is the same. Returns true if the same, otherwise false is returned.

When you use the Equals () method to compare two strings, the case for the characters is also within the scope of the check.

Note: In Java, the double equals (= =) and Equals () methods are applied to both strings, but the content of the judgment is different. Simply put, "= =" Determines whether the first address of two string objects in memory is equal, that is, whether the same string object is judged, and equals () determines whether the values of two string objects are equal.

3. Method provided by the string class--Comparison of strings (ignoring case)

Grammar:

String. Equalsignorecase (string 2);

Ignores case comparison string 1 and string 2. Returns true if all are the same; false otherwise.

4. The method provided by the string class-the conversion case of the string

Grammar:

String. toLowerCase ()

Returns the lowercase form of a string

String. toUpperCase ()

Returns the uppercase form of a string

toLowerCase (): The English letter in the converted string is lowercase. Java→java

toUpperCase (): The English letter in the converted string is uppercase. Java→java

Modify the code in the example as follows, you can also implement login ignoring case.

if (Uname.equals ("TOM"). toLowerCase ()) &&pwd.equals (("1234567"). toUpperCase ())) {

System.out.print ("Login Successful! ");

}else{

System.out.print ("User name or password does not match, Login failed!") ");

}

1. Complex string processing--Connection string

There are two ways to concatenate strings: Use the "+" operator, and use the concat () method of the String class.

(1) You can use the "+" operator to connect when defining a string. such as: System.out.println ("SQL:" +sqlscore+ "Java:" +javascore+ "HTML:" +htmlscore);

When you use the "+" operator to concatenate strings and int (or double) type data, "+" automatically converts the int (or double) type data to a string type.

(2) In addition, in Java, the string class also provides another method, the Concat () method, to concatenate a string to the back of another string, with the following syntax.

Grammar:

String 1.concat (string 2);

String 2 is concatenated to the back of string 1, returning the new string after the connection.

Using this method, let the computer greet you with the code as shown below.

String S=new string ("Hello,");

String Name=new string ("Zhang San! ");

String Sentence=s.concat (name);

System.out.println (sentence);

After execution, the string sentence content is "Hello, Zhang San!" ", the value of s and name is still" Hello, "," Zhang San ".

2. Complex string processing--extraction and query of strings

The string class provides some common methods for extracting and querying.

Common methods for extracting and querying strings

Ordinal

Method

Description

1

public int indexOf (int ch)

public int indexOf (String value)

Searches for the first occurrence of the character ch (or string value)

2

public int lastIndexOf (int ch)

public int LastIndexOf (string value)

Searches for the last occurrence of the character ch (or string value)

3

public string substring (int index)

Extract string portion starting from position index

4

public String substring (int beginindex,int endindex)

Extract the string part between Beginindex and Endindex

5

public string t Rim ()

Returns a copy of the call string with no spaces before or after

The string is a sequence of characters, each character has its own position, and the string is in fact an array of characters, so his position ends at 0 (string length-1). such as the string "Youth without Regrets", of which the "green", "Spring", "no", "regret" the index followed by 0, 1, 2, 3.

In the table of methods used to extract and query strings in common, the 4 methods in the previous 1, 2 are performing a search operation, and 4 of the following 3, 5, 3 methods are used to extract characters or strings.

(1) indexOf () method

The method is to search for a specified character or string within a string, which returns the position where the first matching character appears. If no match is found, 1 is returned. When called, the parentheses indicate the name of the character (or string) to search for. For example, search for "Youth without regrets" in the character "spring" position.

String s= "Youth Without Regrets";

int Index=s.indexof (' Spring ');

After execution, the position of the return character "Spring" is 1.

(2) LastIndexOf () method

The method also searches for a specified character or string within a string, but it is the position of the last occurrence of the search character (or string). For example, the search string "Youth No Regrets Youth no regrets" in the last occurrence of the string "Youth" position.

String s= "Youth without Regrets youth no regrets";

int Index=s.lastindexof (' Youth ');

After execution, returns the first character position of the string "Youth", and the value of index is 6.

(3) substring (int index) method

The method is used to extract the part of the string starting at the position index, which is written in parentheses at the beginning of the string to be extracted, and the return value of the method is the string to extract. For example, to extract the string "No regrets in youth" in the "spring without regrets."

String s= "Youth Without Regrets";

String result=s.substring (1);

(4) substring (int beginindex,int endindex) method

This method is used to extract the string portion between the position beginindex and the position endindex position. In particular, it is important to note that for the start position Beginindex,java is based on the first character of the string for zero, but for the terminating position Endindex,java is based on the first character of the string, as shown in.

0

1

2

3

4

5

6

7

Calculate Start position

Green

Spring

No

Regrets

No

Regrets

Green

Spring

1

2

3

4

5

6

7

8

Calculate End Position

For example, to extract "Youth No Regrets No regrets youth" in the "no Regrets no regrets."

String s= "Youth without regrets and no regrets";

String result=s.substring (2,6);

(5) Trim () method

The method can ignore whitespace before and after the string. When receiving a user-entered string, the trim () method is typically called to filter out extra spaces before and after the string.

3. Complex string processing--splitting of strings

The Java String class provides a method for splitting a string split (), separating a string into substrings, and returning the result as an array of strings.

Grammar:

String 1.split (string separator,int limit);

which

(1) Separator optional, identifies the split string when one or more characters are used. If the item is not selected, an array of elements containing all the individual characters of the string is returned.

(2) The limit option, which is used to limit the number of elements in the returned array.

StringBuffer class

The StringBuffer class is in the Java.lang package and is an enhanced type of string class.

Using the StringBuffer class also requires a two-step completion.

1. Declare the StringBuffer object and initialize it.

Declares an empty StringBuffer object

StringBuffer sb1=new StringBuffer ();

Declare a string "Youth without Regrets"

StringBuffer sb2=new StringBuffer ("Youth Without Regrets");

2. Using StringBuffer objects

The StringBuffer class provides a number of methods for use, called using the "." operator is completed.

Common methods of StringBuffer class

1, Syntax: string 1.toString ();

Converts a string of type StringBuffer 1 to an object of type string and returns.

For example:

String s1=sb2.tostring (); Convert to String class

2, Syntax: String 1.append (String 2);

String 2 is concatenated to string 1 and returned.

This method, like the Concat () method of the String class, appends a string to another string, except that string literals can only be appended to a string. Instead, StringBuffer can append any type of value to the string.

3, Syntax: string 1.insert (position, parameters);

Inserts a parameter into the specified position (int type) of string 1 and returns. The parameter can be any type that includes a string.

S1/using Java to understand program logic/15-strings

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.