Java string & stringbuffer

Source: Internet
Author: User

 

7.1 string
Class
7.2
Stringbuffer
Class

7.1 string
Class
Objects of the string class cannot be changed once they are created.
String constant. In the previous program, we have used the String constant multiple times.
For example, "input a integer data/N" is a character in an output statement.
String constants, but this concept was not explicitly put forward at that time. Learn about the string class
Before reading this document, let's emphasize that you should take this chapter into consideration
The number is different from the character constants we learned in Chapter 2. Character constants are
A single character enclosed in single quotes, for example, 'A', '/N. While string constants use
Character sequences enclosed by double quotation marks, such as "a", "/N", and "Java now. In
In Java, string constants usually exist as objects of the string class,
There is a dedicated data member to indicate its length. This section mainly discusses string objects.
.

7.1.1
Create string
Object
The Java language specifies that string constants must be enclosed in double quotation marks. A string can
Contains letters, numbers, and various special characters, such as +,-, *,/, and $. In our
The preceding program example has used string constants for multiple times, for example, the following statement:
System. Out. println ("OK! ");
"OK! "Is a String constant. Any String constant in Java is string
Class Object, except that Java automatically creates a secret
Objects of the string class. Therefore, they are also called objects of the anonymous string class. Me
You can use the following method to create a string class object. For example:
String C1 = "Java ";

Statement to create the object C1 of the string class, and the anonymous string class is assigned a value.
The object "Java" is assigned to C1 for reference. Once a string class object is created
A dedicated data member to record its length.

7.1.2 string
Class Constructor
Table 7.1 string
Class Constructor
Construction Method description
Public String () creates an empty string object
Public String (string value) creates a new String object with the string object value. The value can be
It is a string or string class object.
Public String (char value []) uses the character array value [] to create a String object.
Public String (char value [], int offset, int
Count)
Starting from the character marked as offset in the value of the character array
String object with Count characters.
Public String (byte ASCII []) uses byte String Array ASCII, according to the default character encoding side
Create a String object.
Public String (byte ASCII [], int offset int
Count ))
Starting from the character marked as offset in ASCII of the byte array, press
The default character encoding scheme creates string objects with Count characters.
Public String (stringbuffer) constructs a new string whose value is the current content of the string.

[Example program c7_1.java] use of seven constructor methods of the string class.
Import java. Io .*;
Public class c7_1
{
Public static void main (string [] ARGs)
{// Character array string
Char chararray [] = {'B', 'I', 'R', 't', 'h', '', 'D', 'A ', 'y '};
// Byte array string. The value of each byte represents the internal code of the Chinese character.
// The internal code of Chinese characters (gb2312). The two bytes are encoded to form a Chinese character.
// Arrays constitute four Chinese characters of "Object-Oriented. -61 and-26 are combined into a Chinese "surface", and the rest are similar.

Byte bytearray [] = {-61,-26,-49,-14,-74,-44,-49,-13 };
Stringbuffer buffer;
String S, S1, S2, S3, S4, S5, S6, S7, SS;
S = new string ("hello"); // Create a New String object s with a string
Ss = "ABC"; // assign a string to a string-type object reference
// Use stringbuffer to create a string Object Buffer
Buffer = new stringbuffer ("Welcom to Java programming! ");
S1 = new string (); // create an empty string object

S2 = new string (s); // use String object s to create a New String object S2
S3 = new string (chararray); // create a String object S3 with a character array
// Create a String object S4 with three characters starting from 6 in the string array
S4 = new string (chararray, 6, 3 );
// Use a string array bytearray to create a String object S5 Based on the default character encoding scheme
S5 = new string (bytearray );
// Starts from the bytearray subscript of the bytearray created earlier and obtains four consecutive characters.
Create a String object
// S6, that is, {-49,-14,-74,-44}
S6 = new string (bytearray, 2, 4 );

// Construct a new String object S7 whose value is the current content of the string buffer
S7 = new string (buffer );
System. Out. println ("S1 =" + S1 );
System. Out. println ("S2 =" + S2 );
System. Out. println ("S3 =" + S3 );
System. Out. println ("S4 =" + S4 );
System. Out. println ("S5 =" + S5 );
System. Out. println ("S6 =" + s6 );
System. Out. println ("S7 =" + S7 );
System. Out. println ("SS =" + SS );
System. Out. println ("buffer =" + buffer );
}
}

The running result is as follows:
S1 =
S2 = Hello
S3 = birth day
S4 = Day
S5 = object-oriented
S6 = forward
S7 = Welcom to Java programming!
Ss = ABC
Buffer = Welcom to Java programming!

7.1.3 string
Common Methods of Classes
Table 7.2 java. Lang. String
Common member Methods
Enable the theory of membership
Public int length () returns the length of the current String object
Public char charat (INT index) returns the character at the int index of the current String object subscript
Public int indexof (INT ch)
Returns the first subscript in the current string that is the same as the specified ch character. If no subscript is found
-1 is returned.
Public int indexof (string STR,
Int fromindex)
Start searching from the current subscript fromindex and return the first and specified word
The subscript of the first letter with the same STR string in the current string.
-1 is returned.
Public string substring (INT beginindex) returns the substring from the subscript beginindex to the end of the string.
Public string substring (INT beginindex,
Int endindex)
Returns the information from the subscript beginindex to the subscript endIndex-1 in the current string.
Substring
Public Boolean equals (Object OBJ) if and only if obj is not null and the current String object and OBJ have the same string
True is returned. Otherwise, flase is returned.

Table 7.2 java. Lang. String
Common member Methods
The public Boolean inclusignorecase (string s) function is similar to equals. The case-insensitive signorecase ignores the case-sensitivity when comparing strings.
Public int compareto (string another_s) compares the size of the two strings. Returns an integer less than, equal to, or greater than zero. Return
The return value depends on whether the string is smaller than, equal to, or greater than another_s.
Public String Concat (string Str) connects the STR string to the end of the current string and returns a new string.
Public String Replace (char oldch,
Char newch) Replace the string's character oldch with the string newch
Public String tolowercase () converts uppercase characters in the string to lowercase characters
Public String touppercase () converts lowercase characters in the string to uppercase characters
Public static string valueof (type variable) returns the string form of the variable value. Type can be a character array
Public static string valueof (char [] data,
Int offset, int count) returns the string of Count characters starting from the subscript offset of the character array data.
Public static string valueof (Object OBJ) returns the object OBJ string
Public String tostring () returns the current string

7.1.4
Access String object
Common member methods used to access String object information are:
Length (): returns the length of the current String object.
Charat (INT index): returns the character at index of the subscript of the current String object.
Indexof (INT ch): returns the first ch in the current string, which is the same as the specified ch.
If no subscript is found,-1 is returned. For example, "ABCD". indexof ("C"); // Value
Is 2. "ABCD". indexof ("Z"); // The value is-1.

Indexof (string STR, int fromindex): from the current subscript fromindex
Start searching, return the first letter that is the same as the specified string 'str' in
Subscript in the current string. If no subscript is found,-1 is returned. For example, "ABCD ".
Indexof ("cd", 0); // The value is 2.
Substring (INT beginindex): returns the value of beginindex in the current string.
The child string from the beginning to the end of the string. For example, string S = "ABCDE". substring (3); // The value of S is
"De ".
Public string substring (INT beginindex, int endindex): When
The substring from the subscript beginindex to the subscript endIndex-1. For example,
String S = "abcdetyu". substring (2, 5); // The value of S is "CDE ".

[Example program c7_2.java]
Public class c7_2
{
Public static void main (string ARGs [])
{String S1 = "Java application ";
Char CC [] = {'J', 'A', 'V', 'A', '', 'A', 'P', 'P ', 'l', 'E','t '};
Int Len = cc. length; // returns the length of the current String object
Int len1 = s1.length ();
Int len2 = "ABCD". Length ();

Char C1 = "12abg". charat (3); // returns the character at the int index of the subscript of the current String object
Char C2 = s1.charat (3 );
// Char C3 = cc. charat (1); error, cannot be used like this
// Returns the first subscript of the current string that is the same as the specified ch character.
Int n1 = "abj". indexof (97 );
Int n2 = s1.indexof ('J ');
Int N3 = "abj". indexof ("BJ", 0 );
Int N4 = s1.indexof ("va", 1 );
// Returns the substring in the current string.
String S2 = "abcdefg". substring (4 );

String S3 = s1.substring (4, 9 );
System. Out. println ("S1 =" + S1 + "Len =" + len1 );
System. Out. println ("cc =" + CC + "Len =" + Len); // you cannot print the content of the CC array element like this
System. Out. println ("ABCD = ABCD" + "Len =" + len2 );
System. Out. println ("C1 =" + C1 + "C2 =" + C2 );
System. Out. println ("n1 =" + N1 + "N2 =" + N2 );
System. Out. println ("N3 =" + N3 + "N4 =" + n4 );
System. Out. println ("S2 =" + S2 );
System. Out. println ("S3 =" + S3 );
}
}

Running result:
S1 = Java application Len = 16
Cc = [c @ 310d42 Len = 11
ABCD = ABCD Len = 4
C1 = B C2 =
N1 = 0 n2 = 0
N3 = 1 N4 = 2
S2 = EFG
S3 = appl

7.1.5
String comparison
Common Methods for comparing string members include: equals (),
Equalsignorecase () and compareto (). Their usage and functions are as follows:
Current String object. Equals (mode string object): if and only when the current String object and the module
String objects are of the same length and contain uppercase and lowercase characters,
Returns true. Otherwise, flase is returned. For example, expression
"Computer". Equals ("computer ")
The result is flase, because the first character is case-insensitive.

Current String object. equalsignorecase (pattern string object ):
The functions of the equalsignorecase () and equals () methods are similar. The difference is that
It is case sensitive to letters. For example, expression
"Computer". equalsignorecase ("computer ")
The result is true.
Current String object. compareto (mode string object): Current String object and Mode
Returns the length difference or
The difference between the Unicode value of the first character.

[Example program c7_3.java] use of the member methods for string comparison.
Public class c7_3
{
Public static void main (string ARGs [])
{String S1 = "Java ";
String S2 = "Java ";
String S3 = "welcome ";
String S4 = "welcome ";
String S5 = "welcoge ";
String S6 = "student ";

Boolean b1 = s1.equals (S2); // S1 is the current String object, S2 is the specified object
Boolean b2 = s1.equals ("ABx ");
Boolean B3 = s3.equals (S4 );
Boolean B4 = s1.equalsignorecase (S2 );
Int n1 = s3.compareto (S4 );
Int n2 = s1.compareto (S2 );
Int N3 = s4.compareto (S5 );
Int d1 = s6.compareto ("St ");
Int D2 = s6.compareto ("student ");
Int D3 = s6.compareto ("studentst1 ");
Int D4 = s6.compareto ("stutent ");
System. Out. println ("S1 =" + S1 + "/ts2 =" + S2 );

System. Out. println ("S3 =" + S3 + "/ts4 =" + S4 );
System. Out. println ("S5 =" + S5 );
System. Out. println ("equals: (S1 = S2) =" + B1 + "/t (S1 = ABx) =" + b2 );
System. Out. println ("equals: (S3 = S4) =" + B3 );
System. Out. println ("repeated signorecase: (S1 = S2) =" + B4 );
System. Out. println ("(S3 = S4) =" + N1 + "/t (S1 <S2) =" + N2 );
System. Out. println ("(S4> S5) =" + N3 );
System. Out. println ("d1 =" + D1 + "/td2 =" + D2 );
System. Out. println ("D3 =" + D3 + "/td4 =" + D4 );
}
}

Running result:
S1 = Java S2 = Java
S3 = welcome S4 = welcome
S5 = welcoge
Equals: (S1 = S2) = false (S1 = ABx) = false
Equals: (S3 = S4) = true
Required signorecase: (S1 = S2) = true
(S3 = S4) = 0 (S1 <S2) =-32
(S4> S5) = 6
D1 = 5 D2 = 0
D3 =-3 D4 =-16

7.1.6
String operation
String operation is to use an existing String object to generate a new String object.
Common member methods include Concat (), replace (), tolowercase (),
Touppercase ().
[Example program c7_4.java] string connection, replacement, and case-insensitive Conversion
Change operation.
Public class c7_4
{
Public static void main (string ARGs [])
{String S1 = "Java ";
String S2 = "Java ";
String S3 = "welcome ";

String S4 = "welcome ";
String S5 = "welcoge ";
String SC1 = s3.concat (S1); // The value of SC1 is "Welcome Java"
String SC2 = s1.concat ("ABx ");
String SR1 = s3.replace ('E', 'R'); // replace 'E' in S3 with 'R'
String W1 = s5.tolowercase (); // replace uppercase and lowercase letters in S5
String U2 = s2.touppercase (); // replace lowercase letters in S2 with uppercase letters.
System. Out. println ("S1 =" + S1 + "/ts2 =" + S2 );
System. Out. println ("S3 =" + S3 + "/ts4 =" + S4 );

System. Out. println ("S5 =" + S5 );
System. Out. println ("S3 + S1 =" + SC1 );
System. Out. println ("S1 + ABx =" + SC2 );
System. Out. println ("s3.replace ('E', 'R') =" + SR1 );
System. Out. println ("s5.tolower =" + W1 );
System. Out. println ("s2.toupper =" + U2 );
}
}

Running result:
S1 = Java S2 = Java
S3 = welcome S4 = welcome
S5 = welcoge
S3 + S1 = welcomejava
S1 + ABx = javaabx
S3.replace ('E', 'R') = wrlcomr
S5.tolower = welcoge
S2.toupper = Java

7.1.7
Convert other types of data to strings
The valueof (parameter) member method in the string class can convert the data of the parameter type
Convert to a string. The types of these parameters can be boolean, Char, Int,
Long, float, double, and object.
[Example program c7_5.java] converts other types of data to strings.
Public class c7_5
{
Public static void main (string ARGs [])
{Double M1 = 3.456;
String S1 = string. valueof (M1); convert a double value to a string
Char [] cc = {'A', 'B', 'C '};

String S2 = string. valueof (CC); // converts a character array to a string.
Boolean F = true;
String S3 = string. valueof (f); // convert a Boolean value to a string
Char [] cs = {'J', 'A', 'V', 'A '};
String S4 = string. valueof (CS, 2, 2 );
System. Out. println ("M1 =" + M1 + "/ts1 =" + S1 );
System. Out. println ("S2 =" + S2 );
System. Out. println ("F =" + F + "/ts3 =" + S3 );
System. Out. println ("S4 =" + S4 );
}
}

Running result:
M1 = 3.456 S1 = 3.456
S2 = ABC
F = true S3 = true
S4 = va

[Example program c7_6.java] valueof (object) member method and tostring ()
The member method is used together to return the character representation of the object.
Class A1
{Int X, Y;
A1 (int x, int y) {This. x = x; this. Y = y ;}
Public String tostring () {return ("/Tx =" + x + "/t, y =" + Y );}
}
Public class c7_6
{
Public static void main (string ARGs [])

{A1 P = new A1 (); // call the constructor to initialize
// String. valueof (p) returns the character representation of the P object. Valueof (p) Reference
// Tostring () member method. The P object can be converted to a string using the tostring () member method.
String STR = string. valueof (P );
System. Out. println ("str =" + Str );
}
}
Running result:
STR = x = 2, y = 6

7.1.8 main
Parameters in the Method
In Java applications, we must write public static void main (string []
ARGs) main method. One parameter in the main method is the string array args.
ARGs [0], argS [1]... The value of argS [N] is a string. ARGs is life
The parameter of the line. When the Java interpreter interprets a user's bytecode file, it can include
Parameters that need to be passed to the main method. The general format is:
Java class file name string 1 string 2 ...... String n
The class file names and strings are separated by spaces.

[Example program c7_7.java] enter the main method of the parameter when running.
Public class c7_7
{
Public static void main (string [] ARGs)
{
For (INT I = 0; I <args. length; I ++)
System. Out. println (ARGs [I]);
}
}

Enter "Java c7_7 Hello world let's Java!" at runtime !" Command, there are
The result is as follows:
Hello
World
Let's
Java!

7.2
Stringbuffer
Class
The stringbuffer class (string buffer class) is also a child of Java. Lang. object.
Class. Different from the string class, the stringbuffer class can be changed during operations.
Content string class, that is, once the stringbuffer class object is created
To modify and change the content of a string. That is to say, for stringbuffer class objects
Not only can search and compare operations, but also can add, insert, modify and so on
.

7.2.1
Create stringbuffer
Object
Table 7.3
Stringbuffer
Constructor
Constructor Theory
Public stringbuffer () creates an empty string buffer with a default initial length of 16 characters
Public stringbuffer (INT length) creates an empty string buffer with the initial length specified by length
Public stringbuffer (string Str) creates a string buffer with the specified string Str. The length of the buffer is the length of the STR plus 16.
Characters

7.2.2
Stringbuffer
Common Methods of Classes
Table 7.4
Java. Lang. stringbuffer
Common member Methods
Enable the theory of membership
Public int length () returns the length of the string in the current buffer.
Public char charat (INT index) returns the character at the index of the string subscript in the current buffer.
Character
Public void setcharat (INT index, char ch) returns the character at the index of the string subscript in the Current Buffer
Change to the CH value.
Public int capacity () returns the Current Buffer Length
Public stringbuffer append (Object OBJ) adds the string returned by obj. tostring () to the current
Unended string
Public stringbuffer append (type variable) converts the variable value to a string and adds it to the current character.
The string is not at the end. The type can be a character array, string, and each
Basic Types

Table 7.4
Java. Lang. stringbuffer
Common member Methods
Public stringbuffer append (char [] STR, int
Offset, int Len)
Returns the Len characters starting from the subscript offset.
Add the string to the end of the current string in sequence
Public stringbuffer insert (INT offset, Object
OBJ)
Insert the string returned by obj. tostring () into
Prefix subscript offset
Public stringbuffer insert (INT offset, Type
Variable)
Convert the variable value to a string and insert it to the current
Position where the character array subscript is offset
Public String tostring () converts a variable string to an immutable string.

7.2.3
Stringbuffer
Class test buffer Length Method
The stringbuffer class provides members such as length (), charat (), and capacity ().
Method to test the buffer length.
[Example program c7_8.java] test the buffer length.
Public class c7_8
{
Public static void main (string [] ARGs)
{
Stringbuffer buf1 = new stringbuffer (); // create an empty string buffer
// Create an empty string buffer with an initial length of 16
Stringbuffer buf2 = new stringbuffer (10 );

// Create a string buffer with the specified "hello" String
Stringbuffer buf3 = new stringbuffer ("hello ");
// Returns the length of the current string.
Int len1 = buf1.length ();
Int len2 = buf2.length ();
Int len3 = buf3.length ();
// Return the Current Buffer Length
Int le1 = buf1.capacity ();
Int le2 = buf2.capacity ();
Int le3 = buf3.capacity ();

// Remove 3 characters from the buf3 string
Char CH = buf3.charat (3 );
// Use the tostring method of stringbuffer to convert the three stringbuffer
// Convert the object to string object output
System. Out. println ("buf1 =" + buf1.tostring ());
System. Out. println ("buf2 =" + buf2.tostring ());
System. Out. println ("buf3 =" + buf3.tostring ());
System. Out. println ("len1 =" + len1 + "/tlen2 =" + len2 + "/tlen3 =" + len3 );
System. Out. println ("le1 =" + le1 + "/tle2 =" + le2 + "/tle3 =" + le3 );
System. Out. println ("Ch =" + CH );
}
}

Running result:
Buf1 =
Buf2 =
Buf3 = Hello
Len1 = 0 len2 = 0 len3 = 5
Le1 = 16 le2 = 10 le3 = 21
Ch = L

7.2.4
Stringbuffer
Class append ()
Method
The stringbuffer class provides append (Object OBJ) and append (Type
Variable) and append (char [] STR, int offset, int Len) member methods. Reader Kegen
You can use either of the following methods to convert a parameter to a string and add it to the current character.
String.
[Example program c7_9.java] adds a given string to the end of the current string.
Public class c7_9
{
Public static void main (string [] ARGs)
{

Object x = "hello ";
String S = "good bye ";
Char CC [] = {'A', 'B', 'C', 'D', 'E', 'F '};
Boolean B = false;
Char c = 'Z ';
Long K = 12345678;
Int I = 7;
Float F = 2.5f;
Double D = 33.777;
Stringbuffer Buf = new stringbuffer ();

Buf. append (x); Buf. append (''); Buf. append (s );
Buf. append (''); Buf. append (CC); Buf. append ('');
Buf. append (CC, 0, 3); Buf. append (''); Buf. append (B );
Buf. append (''); Buf. append (c); Buf. append ('');
Buf. append (I); Buf. append (''); Buf. append (k );
Buf. append (''); Buf. append (f); Buf. append ('');
Buf. append (d );
System. Out. println ("Buf =" + BUF );
}
}
Running result:
Buf = Hello Good bye abcdef ABC false Z 7 12345678 2.5

7.2.5
Stringbuffer
Insert ()
Method
The stringbuffer class provides insert (INT offset, object OBJ) and insert (int
The offset, type variable) member method is used to insert a string to the current string,
The offset parameter specifies the insert position.
[Example program c7_10.java] converts various data into strings and inserts them
The first 0th positions of the string.
Public class c7_10
{
Public static void main (string [] ARGs)
{
Object y = "hello ";
String S = "good bye ";

Char CC [] = {'A', 'B', 'C', 'D', 'E', 'F '};
Boolean B = false;
Char c = 'Z ';
Long K = 12345678;
Int I = 7;
Float F = 2.5f;
Double D = 33.777;
Stringbuffer Buf = new stringbuffer ();
Buf. insert (0, Y); Buf. insert (0, ''); Buf. insert (0, S );
Buf. insert (0, ''); Buf. insert (0, CC); Buf. insert (0 ,'');
Buf. insert (0, B); Buf. insert (0, ''); Buf. insert (0, C );

Buf. insert (0, ''); Buf. insert (0, I); Buf. insert (0 ,'');
Buf. insert (0, k); Buf. insert (0, ''); Buf. insert (0, F );
Buf. insert (0, ''); Buf. insert (0, d );
System. Out. println ("Buf =" + BUF );
}
}
The running result is as follows:
Buf = 33.777 2.5 12345678 7 Z false abcdef good bye Hello

7.2.6
Stringbuffer
Class setcharat
()
Method
The setcharat (INT index, char ch) method is to place the index of the subscript of the current string
To the CH value.
[Example program c7_11.java]
Public class c7_11
{
Public static void main (string [] ARGs)
{Stringbuffer Buf = new stringbuffer ("Hello there ");
System. Out. println ("Buf =" + Buf. tostring ());
System. Out. println ("char at 0:" + Buf. charat (0 ));

Buf. setcharat (0, 'H'); // rewrite the character with the subscript of the Buf string to 'H'
Buf. setcharat (6, 'T'); // rewrite the character whose subscript is 6 to 'T'
System. Out. println ("Buf =" + Buf. tostring ());
}
}
The running result is as follows:
Buf = Hello there
Char at 0: H
Buf = Hello there

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.