Strings in Java

Source: Internet
Author: User

The following is referenced from http://wiki.jikexueyuan.com/project/java/strings.html:

String, which is widely used in Java programming, is a sequence of characters. In the Java programming language, a string is an object.

The Java platform provides a string class to create and manipulate strings.

First, create a string

The most straightforward way to create a string is to write this:

String greeting = "Hello world!";

When a string is created, the compiler creates a string object with its value in this case, such as: "Hello world!."

Any other object can be created by using the New keyword and by constructing a string object. The string class has 11 constructors that provide initial values, such as a character array, that use different types of strings.

 Public class stringdemo{   publicstaticvoid  main (String args[]) {      Char [] Helloarray = {' h ', ' e ', ' l ', ' l ', ' o ', '. ' };       New String (helloarray);        System.out.println (hellostring);   }} // this produces the following result:hello.

Note: The string class is immutable, so it cannot be changed once the string object is created. If you need a large number of strings to modify characters, you should use the StringBuffer and StringBuilder classes.

Second, string length

The method used to obtain information about an object is called an access method. An access method that can be used with a string is length (), which returns the number of characters contained in the string object.

After the following two lines of code are executed, Len equals 17:

 Public class Stringdemo {   publicstaticvoid  main (String args[]) {      = "Dot saw I Was Tod ";       int len = palindrome.length ();      " String Length is: "+ len);}   } // this will produce the following results: String Length is:17

Third, connection string

The string class includes a method for connecting two strings:

String1.concat (string2);

This returns a new string that adds string2 at the end of the string1. You can also use the concat () method to concatenate strings, such as:

"My name is". Concat ("Zara");

Strings are more commonly concatenated with the "+" operator, such as:

"Hello," + "world" + "!"

This will produce:"Hello, world!"

Take a look at the following example:

 Public class Stringdemo {   publicstaticvoid  main (String args[]) {      = ' Saw I was ' ";      System.out.println ("Dot" + string1 + "Tod");}   } // this will produce the following results: Dot saw I was Tod

Iv. creating a formatted string

There are already printf () and format () methods to print numbers in the output format. The string class has an equivalent method, format (), which returns a string object instead of a PrintStream object.

The static format () method that uses strings allows you to create reusable format strings instead of a one-time print statement. For example, if you replace the following methods:

System.out.printf ("The value of the float variable is" +                  "%f and while the value of the" +                  "variable is%d, and the string "+                  " is%s ", Floatvar, Intvar, stringvar);

It can be written like this:

= String.Format ("The value of the float variable is" +                   "%f, while the value of the integer" +                   "variable is%d, a nd the string "+                   " is%s ", Floatvar, Intvar, stringvar); SYSTEM.OUT.PRINTLN (FS);

V. String method

Here is a list of methods supported by the String class:

Method Description
char charAt (int index) Returns the character at the specified index.
int CompareTo (Object o) Compares this string to another object.
int CompareTo (String anotherstring) Compares a dictionary order of two strings.
int comparetoignorecase (String str) Compares two strings in dictionary order, with a case-insensitive difference.
String concat (String str) Concatenates the specified string to the end of the string.
Boolean contentequals (StringBuffer SB) Returns true if and only if the string represents the same sequence of characters as the specified stringbuffer.
Static String copyvalueof (char[] data) Returns a string representing the sequence of characters in the specified array.
Static String copyvalueof (char[] data, int offset, int count) Returns a string representing the sequence of characters in the specified array.
Boolean endsWith (String suffix) Tests whether this string ends with the specified suffix.
Boolean equals (Object anobject) Compares this string with the specified object.
Boolean equalsignorecase (String anotherstring) Compare this string to another string, ignoring case considerations.
Byte GetBytes () Decodes this string by using the platform's default character set and storing the result into a new byte array in a sequence of bytes.
Byte[] GetBytes (String charsetname Decodes this string to a sequence of bytes using the specified character set and stores the result in a new byte array.
void GetChars (int srcbegin, int srcend, char[] DST, int dstbegin) Copies characters from this string to the target character array.
int Hashcode () Returns a hash code for this string.
int indexOf (int ch) Returns the index at which this string specifies the first occurrence of a character.
int indexOf (int ch, int fromIndex) Returns the index in this string where the specified character first appears, starting the search at the specified index.
int indexOf (String str) Returns the index at which this string specifies the first occurrence of a substring.
int indexOf (String str,int fromIndex) Returns the index at 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 at which this string specifies the last occurrence of a character.
int lastIndexOf (int ch, int fromIndex) Returns the index at which this string specifies the last occurrence of a character, and searches backwards from the specified index.
int lastIndexOf (String str) Returns the index of this string that specifies the rightmost occurrence of the substring.
int lastIndexOf (String str, int fromIndex) Returns the last occurrence of the specified substring in the string, searching backward from the beginning of the specified index.
int Length () Returns the length of this string.
Boolean matches (String regex) Determines whether this string matches a given regular expression.
Boolean Regionmatches (boolean ignoreCase, int toffset, String other, int ooffset, int len) The area that tests two strings equals.
Boolean regionmatches (int toffset, String other, int ooffset, int len) The area that tests two strings is equal.
String replace (char OldChar, char Newchar) Return from Newchar replace Oldchar all occurrences of a new string generated in this string.
String ReplaceAll (string regex, string replacement) Replaces each substring of the given regular expression in this string that matches the given substitution.
String Replacefirst (string regex, string replacement) Replaces this string to match the given regular expression given the replacement of the first substring.
String[] Split (String regex) Splits the string around the given regular expression.
String[] Split (String regex, int limit) Splits the string around the given regular expression.
Boolean startsWith (String prefix) Tests whether this string begins with the specified prefix.
Boolean startsWith (String prefix, int toffset) Tests whether this string begins with the specified prefix at the beginning of the specified index.
Charsequence subsequence (int beginindex, int endIndex) Returns a new sequence of characters, a subsequence of this sequence.
String substring (int beginindex) Returns a new string that is a substring of this string.
String substring (int beginindex, int endIndex) Returns a new string that is a substring of this string.
Char[] ToCharArray () This string is converted to a new character array.
String toLowerCase () The rule for all characters in this string uses the default locale lowercase.
String tolowercase (locale locale) The rules for all characters in this string use the given locale in lowercase.
String toString () This object (it is already a string!) ) returns a string form (this is itself).
String toUpperCase () Converts all characters in this string to uppercase using the rules of the default locale.
String touppercase (locale locale) Converts all characters in this string to uppercase using the rules for the given locale.
String Trim () Returns a copy of the string, beginning and ending with whitespace removal.
Static String valueOf (primitive data type X) Returns a string representation of the passed data type parameter.

Test Project: Https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test9

Strings in Java

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.