"Javase" day01_ API documentation, string Basic operations

Source: Internet
Author: User

"Javase" day01_ API documentation, string Basic operations

--20150820


1.String and its common APIs1) In Java, a string object is an immutable object, and once created in memory, the content cannot be changed, and a new object is created to change the contents of the string. This is done to minimize the overhead of system resources by reusing strings of the same content to the maximum extent possible.


2) string constant pool

when we initialize a string by literal, constant, the JVM first starts from the Chang of the string (a memory area maintained within a JVM, which is used to hold a string object that has already been created), and the object that is used to hold the string is present, and if it exists, it is directly referenced. If it does not exist, create the string object and store it in a constant pool, and then reference it. Because the string content cannot be changed, we can safely reuse them.


3) memory encoding and length


Java store each character is saved with 2 bytes, using Unicode encoding. And any character, whether English or Chinese, has a length of 1. So the length of the string is the number of characters in the string.

int length (): Returns the length of the current string.

For example:

Package day01;/** * int lenght () * Gets the number of characters in the current string (length), both Chinese and English * Each character occupies two bytes (Unicode encoding) * @author soft01 * */public class Strin Glengthdemo {public static void main (string[] args) {String str = "I love, Java"; System.out.println (Str.length ()); 7}}



4) indexof Implementation Search

int indexOf (int ch): Used to check the index position of the first occurrence of a given character in the current string. The subscripts and arrays here are similar, 0 means the 1th character of the string, and so on. When the string does not contain the given character, the method returns-1.

For example:
Package day01;/** * int indexOf (string str) * Finds the position of the given string for the first time in the current string. * The return value for the given string the first character in the current string subscript * is sensitive to Java case, so it must be matched on all to return the specific subscript. Otherwise returns-1 * @author soft01 * */public class Indexofdemo {public static void main (string[] args) {String str = ' Thinking in Ja VA ";//check in position int index = Str.indexof (" in "); SYSTEM.OUT.PRINTLN (index); 2/* * Overloaded Method: * INDEXOF (String str,int from) * Finds the position of the first occurrence of the given string, starting at the specified subscript position in the current string. * Similarly, if no return-1 is found. */index = Str.indexof ("in", 2); Subscript System.out.println (index); 2index = Str.indexof ("in", 3); SYSTEM.OUT.PRINTLN (index); 5/* * int lastIndexOf (string str) * Finds the position of the last occurrence of the given string in the current string. */index = Str.lastindexof ("in"); SYSTEM.OUT.PRINTLN (index); 9/* * In practice, it is often used to check if a string appears * the required keyword, or even to determine the location to use. */}}



5) substring get substring

string substring (int begin,int end): Used to intercept part of the current string to get the substring. We only need to pass in two integers, one to indicate where to start, and another to indicate where to intercept. The position here is to be represented by the subscript of the string, and note that these two numbers represent a range of "with heads without Tails", in other words, characters that contain the starting subscript, but do not contain the characters that end the subscript.

For example:

Package day01;/** * Get some of the contents of a String * substring (int start,int end) * Start with the corresponding character at the specified subscript start, intercept the string between the specified subscript end *, and note that the character that does not contain the end position 。 * The Java API generally uses 2 numbers to denote a range, usually "with head without tail". *  * @author soft01 * */public class Substringdemo {public static void main (string[] args) {String str = "www.baidu.com "; System.out.println (Str.length ()); 13String substr1 = str.substring (4,9); System.out.println (SUBSTR1); Baidustring substr2 = str.substring (4,13); Str.length () -13system.out.println (SUBSTR2); baidu.com////a parameter, from the specified subscript to the end of string SUBSTR3 = Str.substring (4); System.out.println (SUBSTR3); Baidu.com}}



6) Trim ()

String Trim (): The whitespace on either side of the string (there are many kinds of whitespace, the space is one of them) is removed and the new string is returned to us.

For example:
Package day01;/** * String trim () * Removes whitespace from both sides of the current string * @author soft01 * */public class Trimdemo {public static void main (Stri Ng[] args) {String str = "    Hello world"; System.out.println (str); String trim = Str.trim (); System.out.println (Trim); System.out.println ();}}




7) CharAt ()

char charAt (int index): used to get the character of this position in the string given a subscript position.

For example:

Package day01;/** * Char charAt (int index) * Gets the character corresponding to the specified position (subscript) in the current string * @author soft01 * */public class Charatdemo {public St atic void Main (string[] args) {String str = "thinking in Java"; char C = str.charat (0); System.out.println (c); T}}



8) StartsWith and EndsWith

Boolean startsWith (string suffix): Used to determine whether the current string starts with the given string. It's important to note that capitalization is sensitive.

Boolean endsWith (string suffix): Used to determine whether the current string ends with the given string.

For example, we can use EndsWith () to determine whether the file is a picture based on the name of a file, such as ". jpg", ". gif", and so on.

For example:
Package day01;/** * Boolean startsWith (String str) *--Determines whether the current string starts with a given string * Boolean EndsWith (String str) *--Determines whether the current string is given The string at the end of the * @author soft01 * */public class Startswithdemo {public static void main (string[] args) {string str = "thinking I n java "; Boolean starts = Str.startswith (" think "); System.out.println (starts); Trueboolean end = Str.endswith ("va"); SYSTEM.OUT.PRINTLN (end); True}}




9) Uppercase and lowercase transformations

String toUpperCase (): Used to capitalize all the characters in the English part of the current string and return the new string

String toLowerCase (): Used to change the characters of the English part of the current string all to lowercase before returning the new string

For example, we often ask us to enter a verification code on the Internet, the image in English may be uppercase, but we do not need to enter the exact case input, but still can verify success. This is effective in this approach. We can convert all the input verification codes to uppercase, and then compare all the displayed content in the picture to uppercase.

For example:
Package day01;/** * String toUpperCase () * String toLowerCase () * Converts the English part of the current string to uppercase and all lowercase. * @author soft01 * */public class Touppercasedemo {public static void main (string[] args) {String str = "I love Java1.8"; String upper = Str.touppercase (); SYSTEM.OUT.PRINTLN (upper); String lower = Str.tolowercase (); System.out.println (lower);//usually used to ignore case-sensitivity (for example, Verification Code judgment)}}




Ten) ValueOf ()

The string provides a number of overloaded valueof () methods that can describe the values of other primitive types as strings.

static string valueOf (int i): Returns the string representation of the int parameter
static string ValueOf (Boolean B): Returns the string representation of a Boolean parameter
static string valueOf (char c): Returns the string representation of a char parameter
static string valueOf (double D): Returns the string representation of a double argument
static string ValueOf (char[] c): Returns the string representation of a char array parameter
static string ValueOf (char[] c,int offset,int count): Returns the string representation of a specific subarray of char array parameters.
static string ValueOf (float): Returns the string representation of the float parameter
static string valueOf (long L): Returns the string representation of a long parameter
static string ValueOf (Object O): Returns the string representation of the object argument

For example:

Package day01;/** * static string ValueOf () * String provides a number of static methods valueOf () * function is to convert other types to strings. * More commonly used is to convert the base type to a string. *  * @author soft01 * */public class Valueofdemo {public static void main (string[] args) {int a = 123; String S1 = string.valueof (a); "123" System.out.println (S1+4); "1234" System.out.println (A+4); 127system.out.println (A + "" +4); "1234" double d = 123.123; String s2 = string.valueof (d); "123.123" System.out.println (s2+4); "123.1234" System.out.println (d+4); 127.123String s3 = 123+ ""; No string.valueof (a) High efficiency}}



2. StringBuilder and its common APIs1) StringBuilder package variable string

We have learned from the string class that it is an immutable object, so the creation of new objects is thrown whenever the content is modified. So when we have a need to frequently modify the string, this does not only not reduce the memory overhead, the return will increase the memory overhead. For this purpose Java provides us with a class specifically designed to modify the contents of a string: StringBuilder.

The class encapsulates a mutable string, in other words, when we need to change the contents of the string, we do not create a new object, but rather modify it on the basis of the original object. This reduces the overhead of memory.


2) Common methods of StringBuilder

Common methods of the StringBuilder class are:

Append (String str): Append string;
Insert (int dstoffset,string s): Insert string;
Delete (int start,int end): delete string;
replace (int start,int end,string str): replace string;
Reverse (): string inversion.

3) StringBuilder

The return values for many methods of StringBuilder are StringBuilder types. The return statements for these methods are: return this.

The object's reference was returned because it changed the encapsulated character sequence. You can write the code in the following concise way:

Buf.append ("IBM"). Append ("Java"). Insert (3, "Oracle"). Replace (9, "Java");
System.out.println (Buf.tostring ());

4) using Append to implement append

StringBuilder Append (String): Used to append the given string to the end of the current string.



5) inserting with insert implementation

StringBuilder Insert (int offset, string str): Used to insert the given string into the specified position. This position is also the subscript for the string.



6) Delete is implemented using delete

StringBuilder Delete (int start,int end): Used to delete some of the contents of a given string. You need to pass in two parameters that describe the range of strings to be deleted, and the same range is "with head without tail"



7) StringBuilder Summary

StringBuilder is a mutable string. The content calculation of the string, it is recommended to use StringBuilder implementation, so performance will be better.

The process of string connection in Java is implemented using StringBuilder, as shown in the following code:

String s = "AB"; String S1 = s + "DE" +1;
String S1 =
New StringBuilder (s). Append ("DE"). Append (1). ToString ();

8) The difference between StringBuffer and StringBuilder:

StringBuffer is thread-safe, synchronous processing, slightly slower performance;

StringBuilder is non-thread-safe, concurrently processed, with slightly faster performance


Code Demo:

Package day01;/** * Java.lang.StringBuilder * maintains a variable array of characters internally. To address the performance loss caused by the frequent modification of the * string content.  * Internal provides related methods for editing strings: * Additions and deletions * * @author soft01 * */public class Stringbuilderdemo {public static void main (string[] args) {String str = "Hard to learn Java, in order to find a good job!" "; StringBuilder sb1 = new StringBuilder (); "" StringBuilder sb = new StringBuilder (str); It can also be a string of direct volume//system.out.println (Sb.hashcode ());/* * Try to learn Java, in order to find a good job! and change the world! * StringBuilder Append (string str) * Appends the given content to the end of the current string */sb.append ("Then change the world! "); str = sb.tostring (); System.out.println (str);//system.out.println (Sb.hashcode ());/* * Try to learn Java in order to change the world! * StringBuilder Delete (int start,int end) * Deletes the string */sb.delete (11,19) in the given range in the current string; str = sb.tostring (); System.out.println (str); StringBuilder SB2 = sb;/* * Hard to learn Java, just to change the world! * StringBuilder Insert (int offset,string str) * Inserts the given string contents at the specified position */sb.insert (9, "yes"); str = sb.tostring (); System.out.println (str);//system.out.println (SB2==SB);//system.out.println (SB2); * * Alive, just to change the world! * StringBuilder replace (int start,int ENd,string str) * Replace the string in the current string with the given string */sb.replace (0,8, "alive"); str = sb.tostring (); System.out.println (str);/* string reversal */sb.reverse (); str = sb.tostring (); System.out.println (str);}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Javase" day01_ API documentation, string Basic operations

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.