[Java] String

Source: Internet
Author: User
Tags float double

1. Immutable string

The string object is immutable, and every method in the string class that appears to modify a string value is actually creating a completely new string object, such as:

public class Immutable {public static string upcase (string s) {return s.touppercase ();    } public static void Main (string[] args) {String str1 = "String1";    String str2 = upcase (STR1);    System.out.println (STR1);  System.out.println (STR2); }}

When you pass the str1 to the UpCase () method, a copy of the reference is actually passed. Whenever a string object is used as a parameter to a method, a reference is copied. You can add any number of aliases to a string object, and any reference to it cannot change its value. The "+" and "+ =" for string are the only two overloaded operators in Java, and Java does not allow programmers to reload any operators. The operator "+" can be used to concatenate strings, for example:

String mango = "Mango"; String s = "abc" + Mango + "def" + 47; System.out.println (s);


2. String manipulation

Here are some basic methods that the string object has:

Method Parameters Application
Length ()

The number of characters in string
CharAt () int index Gets the char at the string index position
GetChars (), GetBytes () Copy part start and end index, target array, target array start index Copy char or byte to the destination array
ToCharArray ()
Generate a char[]
Equals (), Equalsignorecase () String that is compared Compares two string contents
CompareTo () String that is compared Compare string content by dictionary order
Contains () Charsequence to search for Whether the string object contains parameter contents
Contentequals () Charsequence or StringBuffer for comparison String is exactly the same as the parameter contents
Equalsignorecase () String that is compared Ignore Case comparison content
Regionmatcher () The index offset of the string, the other string and the index offset, the comparison length Whether the comparison area is equal
StartsWith () Possible starting string Whether string starts with this parameter
EndsWith () Possible suffix string Whether string is suffixed with this parameter
IndexOf (), LastIndexOf ()
Char char and start index; String; String vs. Start index
Whether the string contains parameters
SUBSTRING () Start index, end coordinate Returns the new substring specified by the parameter
Concat ()
The string to connect to Returns a String object after a new connection
Replace () The character to replace, the new character to be substituted Returns the new string object after replacement
toLowerCase toUpperCase ()
Returns a new case-sensitive string object
Trim ()
Returns the deletion of blank new string objects at both ends
ValueOf () Object; Char[]; Boolean Char int Long Float Double Returns a String that represents the contents of the parameter
Intern ()
Generate a reference for each unique character sequence


3. Formatted output

In Java, all new formatting features are handled by the Java.util.Formatter class, which translates the formatted string with the data into the desired result. When you create a formatter object, you need to pass some information to its constructor, for example:

public class Test {private String s;  Private Formatter F;    Public Test (String s, Formatter f) {this.s = s;  THIS.F = f;  } public void Move (int x, int y) {F.format ('%s at (%d,%d) \ n ', S, x, y);    public static void Main (string[] args) {Test t = new Test ("point", New Formatter (System.out));  T.move (1, 2); }}

All formatted text will be output to the System.out,formmatter constructor that can accept multiple output destinations through overloading, although the most commonly used are PrintStream (), OutputStream, and file. When inserting data, if you want to control the space and alignment, you need a more sophisticated format modifier, the syntax is as follows:

%[argument_index$][flags][witdh][.precision]conversion

The most common is to control the minimum size of a domain, which can be implemented by specifying the width, formatter objects by adding spaces when necessary to ensure that a field reaches at least a certain length, is right-aligned by default, and can be changed by using the '-' flag. Relative to width is precision, which is used to indicate the maximum size, which represents the maximum number of output characters when a string is printed when precision is applied to a string, and when the precision is applied to a floating-point number, it represents the digits to be displayed for the fractional portion.

The following table contains the most commonly used type conversions:

D Integer type (decimal) E Floating point number (scientific counting)
C Unicode characters X Integer (hexadecimal)
B Boolean value H hash code (HEX)
S String % Character "%"
F Floating-point number (decimal)


4. Regular expressions

Import the Java.util.regex package and use the static Pattern.compile () method to compile the regular expression, which generates a Pattern object based on a regular expression of type string. Then pass the string you want to retrieve into the Matcher () method of the Pattern object, generating a Matcher object, for example:

public static void Main (string[] args) {for (String Arg:args) {Pattern p = pattern.compile (ARG);      Matcher m = P.matcher (Args[0]); while (M.find ()) {System.out.println ("Match" + m.group () + "at positions" + m.start ()       + "-" + (M.end ()-1)); }    }  }}

The Matcher.find () method can be used to find multiple matches, and find () iterates forward the input string like an iterator.

A group is a regular expression separated by parentheses that can refer to a group based on its number, such as three groups in a (B (C)) d: Group 0 is ABCD, Group 1 is BC, and Group 2 is C. The Machter object provides a series of methods to get group-related trust: public int GroupCount () returns the number of groupings in the pattern of the match, and group No. 0 is not included. The public String group () returns the No. 0 group (the entire match) of the previous match operation. The public String Group (int i) returns the group number specified during the previous match operation.

After the match operation succeeds, start () returns the index of the starting position of the previous match, and End () returns the value of the index plus one for the last character that matches. When the match operation fails, calling start () or end () will produce illegalstateexception.

The compile () method of the pattern class also has another version that accepts a tag parameter to adjust the matching behavior:

Pattern Pattern.compile (String regex, int flag)

The flags are derived from constants in the following pattern classes:

Compile markup Effect
Pattern.canon_eq Two characters they are considered to be matched when they are matched by their full canonical decomposition.
Pattern.case_insensitive (? i) Allowing pattern matching does not have to be case-sensitive.
Pattern.comments (? x) Whitespace is ignored and comments begin with # until the end of the line is ignored.
Pattern.dotall (? s) In this pattern, the expression "." Matches all characters, including line Terminators.
Pattern.multiline (? m) In multiline mode, the expression ^ and $ match the start and end of a line, respectively. ^ also matches the beginning of the input string, and $ also matches the end of the input string.
Pattern.unicode_case (? u) When this tag is specified and the case_insensitive is opened, the case-insensitive match is performed in a manner consistent with the Unicode standard.
Pattern.unix_lines (? d) In., ^, and $, only line terminator \ n is recognized.



This article from "Fangyuan" blog, declined reprint!

[Java] String

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.