Java String Class

Source: Internet
Author: User
Tags locale stringbuffer

Create a string
The simplest way to create a string is as follows:
String greeting = "Rookie Tutorial";
When you encounter a string constant in your code, the value here is "rookie Tutorial", which the compiler uses to create a string object.
As with other objects, you can use keywords and construction methods to create a String object.
The string class has 11 constructor methods that provide different parameters for initializing strings, such as providing a character array parameter:
Stringdemo.java File Code:
public class stringdemo{
public static void Main (String args[]) {
Char[] Helloarray = {' R ', ' U ', ' n ', ' o ', ' o ', ' B '};
String hellostring = new string (Helloarray);
System.out.println (hellostring);
}
}
The results of the above example compilation run as follows:
Runoob
Note: The string class is immutable, so once you create a string object, its value cannot be changed (see part of the note parsing).
If you need to make a lot of changes to the string, you should choose to use the StringBuffer & StringBuilder class.
String length
The method used to get information about an object is called an accessor method.
An accessor method of the string class is the length () method, which returns the number of characters that the string object contains.
After the following code executes, the Len variable equals 14:
Stringdemo.java File Code:
public class Stringdemo {
public static void Main (String args[]) {
String site = "www.runoob.com";
int len = Site.length ();
System.out.println ("Novice Tutorial URL Length:" + len);
}
}
The results of the above example compilation run as follows:
Beginner Tutorial URL Length: 14
Connection string
The string class provides a way to concatenate two strings:
String1.concat (string2);
Returns a new string for the string2 connection string1. You can also use the concat () method on string constants, such as:
"My name is". Concat ("Runoob");
It is more commonly used to concatenate strings using the ' + ' operator, such as:
"Hello," + "Runoob" + "!"
The results are as follows:
"Hello, runoob!."
Here is an example:
Stringdemo.java File Code:
public class Stringdemo {
public static void Main (String args[]) {
String string1 = "Novice Tutorial URL:";
System.out.println ("1," + string1 + "www.runoob.com");
}
}
The results of the above example compilation run as follows:
1. Novice Tutorial Website: www.runoob.com
Creating a formatted string
We know Beijing share capital output formatted numbers can use the printf () and format () methods.
The string class uses the static method format () to return a string object instead of a PrintStream object.
The static method of the String class, format (), can be used to create a reusable format string, not just for one print output at a time.
As shown below:
SYSTEM.OUT.PRINTF (the value of the "floating-point variable is" +
"%f, the value of the integer variable is" +
"%d, the value of the string variable is" +
"Is%s", Floatvar, Intvar, stringvar);
You can write that too.
String FS;
FS = String.Format ("Floating-point variable has a value of" +
"%f, the value of the integer variable is" +
"%d, the value of the string variable is" +
"%s", Floatvar, Intvar, stringvar);
String method
The following are the methods supported by the string class, in more detail, see the Java string API documentation:
SN (ordinal) method description
1 char charAt (int index)
Returns the char value at the specified index.
2 int compareTo (Object o)
Compare this string to another object.
3 int compareTo (String anotherstring)
Compares two strings in a dictionary order.
4 int comparetoignorecase (String str)
Compares two strings in a dictionary order, regardless of case.
5 string concat (String str)
Connects the specified string to the end of this string.
6 Boolean contentequals (StringBuffer SB)
Returns True when and only if the string has the same order of characters as the specified stringbutter.
7 Static String copyvalueof (char[] data)
Returns a String representing the sequence of characters in the specified array.
8 Static String copyvalueof (char[] data, int offset, int count)
Returns a String representing the sequence of characters in the specified array.
9 boolean endsWith (String suffix)
Tests whether this string ends with the specified suffix.
Ten Boolean Equals (Object anobject)
Compares this string to the specified object.
One-by-one Boolean equalsignorecase (String anotherstring)
Compares this string to another string, regardless of case.
Byte[] GetBytes ()
This String is encoded as a byte sequence using the platform's default character set, and the result is stored in a new byte array.
Byte[] GetBytes (String charsetname)
Encodes this String into a byte sequence using the specified character set and stores the result in a new byte array.
getChars void (int srcbegin, int srcend, char[] DST, int dstbegin)
Copies the character from this string to the target character array.
int Hashcode ()
Returns the hash code for this string.
int indexOf (int ch)
Returns the index at which the specified character first appears in this string.
+ int indexOf (int ch, int fromIndex)
Returns the index at the first occurrence of the specified character in this string, starting the search from the specified index.
indexOf int (String str)
Returns the index at which the specified substring first appears in this string.
indexOf Int (String str, int fromIndex)
Returns the index of the first occurrence of the specified substring in this string, starting at the specified index.
String Intern ()
Returns a normalized representation of a string object.
int lastIndexOf (int ch)
Returns the index of the specified character at the last occurrence in this string.
int lastIndexOf (int ch, int fromIndex)
Returns the index of the last occurrence of the specified character in this string, starting at the specified index to reverse-search.
lastIndexOf int (String str)
Returns the index of the rightmost occurrence of the specified substring in this string.
lastIndexOf Int (String str, int fromIndex)
Returns the index of the last occurrence of the specified substring in this string, starting at the specified index to reverse the search.
length int ()
Returns the length of this string.
-Boolean matches (String regex)
Tells whether this string matches a given regular expression.
Boolean Regionmatches (boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.
Regionmatches boolean (int toffset, String other, int ooffset, int len)
Tests whether two string regions are equal.
String replace (char OldChar, char Newchar)
Returns a new string that is obtained by replacing all OldChar that appear in this string with Newchar.
String ReplaceAll (string regex, string replacement
Replaces this string with the given replacement for all substrings that match the given regular expression.
String Replacefirst (string regex, string replacement)
Replaces this string with the given replacement to match the first substring of a given regular expression.
String[] Split (String regex)
Splits this string according to the match of the given regular expression.
String[] Split (String regex, int limit)
Splits the string by matching the given regular expression.
StartsWith boolean (String prefix)
Tests whether this string starts with the specified prefix.
StartsWith Boolean (String prefix, int toffset)
Tests whether the substring starting at the specified index begins with the specified prefix.
Charsequence subsequence (int beginindex, int endIndex)
Returns a new sequence of characters that is a subsequence of this sequence.
PNS String substring (int beginindex)
Returns a new string that is a substring of this string.
substring String (int beginindex, int endIndex)
Returns a new string that is a substring of this string.
Char[] ToCharArray ()
Converts this string to a new character array.
+ String toLowerCase ()
Use the default locale rule to convert all characters in this String to lowercase.
toLowerCase String (locale locale)
Converts all characters in this String to lowercase using the rules for a given Locale.
The String toString ()
Returns the object itself (it is already a string!) )。
String toUpperCase ()
Converts all characters in this String to uppercase using the rules of the default locale.
toUpperCase String (locale locale)
Converts all characters in this String to uppercase using the rules for a given Locale.
String Trim ()
Returns a copy of the string, ignoring leading and trailing blanks.
ValueOf static String (primitive data type X)
Returns a string representation of the x parameter for the given data type type.
Java Character class Java StringBuffer and StringBuilder classes
List of Notes

tianqixinbr/>429***[email protected]

The String class is an immutable parsing, such as:
String s = "Google";
System.out.println ("s =" + s);

s = "Runoob";
System.out.println ("s =" + s);
The output is:
Google
Runoob
The result is a change, but why does the door say that the string object is immutable?
The reason is that s in the instance is just a reference to a String object, not the object itself, when executing s = "Runoob"; A new object "Runoob" was created, and the original "Google" still exists in memory.

Tianqixinbr/>tianqixin
429***[email protected]
11 months ago (02-27) br/> Touni's Little Slave
861***[email protected]
The 1.length () method is for a string, which requires the length () method of a string to be used;
The 2.length property is for an array in Java, and requires that the length of the array be used with its long property;
The size () method in 3.java is said for a generic collection, and if you want to see how many elements the generic has, call this method to view it!
This example demonstrates the use of both methods and a property:
public static void Main (string[] args) {
String []list={"Ma", "Cao", "Yuan"};
String a= "Macaoyuan";
System.out.println (list.length);
System.out.println (A.length ());
List array=new ArrayList (); Br/>array.add (a);
System.out.println (Array.size ());
}
The output value is:
3
9
1
Touni's little slave.
Touni's little slave.
861***[email protected]
Helen
109***[email protected]
1. Format the integer melt Kim:%[index$][identification [minimum width] Conversion mode
The formatted string is composed of 4 parts, the special format often starts with%index$, the index starts from 1, indicates that the index parameter is taken in for formatting, and the meaning of [minimum width] is well understood, that is, the number of digits in the string at the end of the integer conversion. The meaning of the remaining 2 parts:
Identity:
'-' is left-aligned within the minimum width and cannot be used in conjunction with ' 0 padding '
' # ' only applies to 8 binary and 16 binary, 8 when adding a 0,16 in front of the result adds 0x to the front of the result
The ' + ' result always includes a symbol (normally only applies to 10 binary, if the object is BigInteger can be used for 8 binary and 16 binary)
"Positive value before adding a space, negative value before the minus sign (normally only applies to 10, if the object is BigInteger can be used for 8 binary and 16 binary)
' 0 ' result will be filled with zero
', ' applies only to 10 binary, with "," separating every 3 digits
' (' If the argument is negative, the result does not add a minus sign but enclose the number in parentheses (same limit as ' + ').
Conversion Mode:
D-Decimal O-octal x or X-16 binary
The above instructions are too boring, let's look at a few specific examples. It is important to note that most of the identity characters can be used at the same time.
System.out.println (String.Format ("%1$,09d",-3123));
System.out.println (String.Format ("%1$9d",-31));
System.out.println (String.Format ("%1$-9d",-31));
System.out.println (String.Format ("%1$ (9d",-31));
System.out.println (String.Format ("%1$ #9x", 5689));
The result is:
-0003,123
-31
-31
(31)
0x1639
2. Format the floating-point number:%[index$][logo [min. width] [. precision] Mode of conversion
As we can see, the conversion of floating-point numbers has a "precision" option that controls the number of digits after the decimal point.
Identity:
'-' is left-aligned within the minimum width and cannot be used in conjunction with ' 0 padding '
' + ' results always include a symbol
' Positive value plus a space before negative value plus minus sign
' 0 ' result will be filled with zero
', ' separated by ', ' between every 3 digits (for FGG conversions only)
' (' If the argument is negative, the result does not add a minus sign but enclose the number in parentheses (only for EEFGG conversions).
Conversion Mode:
' E ', ' e '--the result is formatted as a decimal number in computer science notation
' F '--the result is formatted as a decimal normal representation
' G ', ' G ' – depending on the case, the automatic selection of the normal representation or scientific notation method
' A ', ' a '--the result is formatted as a hexadecimal floating-point number with significant digits and exponent
3. Format the characters:
Formatting characters is very simple, C is a character, the identity '-' means left-aligned, and nothing else.

Java String Class

Related Article

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.