Java-String class

Source: Internet
Author: User

String ClassOverview of the String class

Look up the description of the string class in the API and discover that the string class represents the strings. All string literals (such as "ABC") in a Java program are implemented as instances of this class.

Demo string

String str = "Oracle";

str = "Oracle";

Continuing the lookup API found that strings are constants, and that their values cannot be changed after they are created, what does that mean? In fact, once the string is determined, the string is generated in the memory area. The string itself cannot be changed , but the address value recorded in the STR variable can be changed.

The essence of a string is an array of characters .

Continue the API discovery, the string has a large number of overloaded construction methods. The creation of a string object can be accomplished through the construction of the string class, so what is the difference between creating an object by using double quotation marks and creating the object in the new way?

String s3 = "ABC";

String S4 = New string ("abc");

System. out. println (S3==S4);//false

System. out. println (S3.equals (S4));//true,

Because string overrides the Equals method, it establishes the same basis for the string's own judgment ( through content )

How is S3 and S4 different?

S3 is created with only one object in memory. This object is in the string constant pool

S4 is created with two objects in memory. A new object in the heap, a string itself object, in a string constant pool

String Class construction method

The constructor method is used to complete the creation of a string object

string S1 = new string ();//Create string object with no content in string

byte[] bys = new byte[]{97,98,99,100};

String s2 = new string (bys); Creates a string object that takes an array element as the contents of a string

String s3 = new String (bys, 1, 3); Creates a string object that takes a subset of the array elements as the contents of the string, the parameter offset to the starting index of the array element, and the parameter length to several elements

char[] CHS = new char[]{' A ', ' B ', ' C ', ' d ', ' e '};

String S4 = new string (CHS); Creates a string object that takes an array element as the contents of a string

String S5 = new String (CHS, 0, 3);//Creates a string object, takes a part of the array element as the contents of the string, the parameter offset to the starting index position of the array element, and the parameter count is a few elements

String s6 = new String ("abc"); Creates a string object with the content of the strings ABC

method Lookup for the string class

There are many common methods in the string class, when we learn a class, do not blindly put all the methods to try to use it, then we should be based on the characteristics of this object to analyze the object should have those functions, so that we apply more convenient.

A string is an object, and its method must be defined around the data that operates on the object. Let's think about what functions are in the string.

  How many characters are there in a string?

String str = "ABCDE";

int len = str.length ();

System.out.println ("len=" +len);

  gets the partial string .

String str = "ABCDE";

String S1 = str.substring (1); Returns a new string that contains all characters starting at the specified position to the end of the string

String s2 = str.substring (2, 4);//Returns a new string with the contents starting at the specified position and ending all characters at the specified position

System.out.println ("str=" +str);

System.out.println ("s1=" +s1);

System.out.println ("s2=" +s2);

1.4 Method Lookup exercises in the String class

In front of you briefly introduced a few strings commonly used methods, the process is mainly to learn how to consult the API, how to find the way you want to use. Next, let's practice the search for the string method.

whether the string begins with the specified string. The end is the same. Case Sensitive

String str = "Stringdemo.java";

Boolean B1 = str.startswith ("Demo");//Determine whether to start with a given string

Boolean b2 = Str.startswith ("String");

Boolean b3 = str.endswith ("Java");//Determines whether to end with a given string

whether the string contains another string .

String str = "ABCDE";

int index = str.indexof ("BCD"); Determines whether the specified string is included, returns the index of the first occurrence of the string, or 1 if it is not included

Boolean b2 = str.contains ("BCD");//Determines whether the specified string is included, contains a return of true, does not contain a return of false

converts a string into an array of characters. or a byte array .

String str = "ABCDE";

char[] CHS = Str.tochararray ();

byte[] bytes = str.getbytes ();

Determine if the contents of two strings are the same

String str = "ABCDE";

String str2 = "ABCDE";

String str3 = "Hello";

Boolean B1 = str.equals (str2);

Boolean b2 = Str.equals (STR3);

Gets the contents of the string object

String str = new string ("Hello");

System.out.println ( str.tostring () );

System.out.pintln (str);

When you print a reference type variable directly, the default invocation of the type is overridden by the ToString method

The following requirements correspond to the method that requires everyone to do their own work in the API to find and use the method.

A string that determines whether the contents of the string are empty

str.isempty ();
gets the position of the first occurrence of the given character in the string
Str.indexof (str1);
gets the character at the specified position in the string
Str.charat (index);
converts the string to a lowercase string
str.tolowercase ();
converts the string to an uppercase string
str.touppercase ();
in the string, replace the given old character with the new character
str.replace (Char_old, char_new);
in the string, replace the given old string with the new string
str.replace (Str_old, str_new);
removes both ends of a string, and the middle does not remove, returning a new string
Str.trim ();

The String class method uses the practice

L Title: Gets the number of uppercase, lowercase, and digits in the specified string.

L Idea: 1. In order to count the number of uppercase letters, lowercase characters, and numbers. Create a variable of 3 counts.

2. In order to get to each character in the string, the string is traversed to get each character.

3. Determine the resulting character, if the character is uppercase, the number of uppercase +1, if the character is lowercase, the number of lowercase letters +1, if the character is a number, the number is +1.

4. Displays the number of uppercase, lowercase, and digits

L Code:

public static void Method (String str) {

int bigcount = 0; Number of uppercase letters

int smallcount = 0; Number of lowercase letters

int numbercount = 0; Number of numbers

for (int i=0; i < str.length (); i++) {

char ch = str.charat (i); Gets the character at the specified position

if (ch>= ' A ' && ch<= ' Z ') {

bigcount++;

} else if (ch>= ' a ' && ch<= ' z ') {

smallcount++;

} else if (ch>= ' 0 ' && ch<= ' 9 ') {

numbercount++;

}

}

System.out.println ("Number of capital letters:" +bigcount);

System.out.println ("Number of lowercase letters:" +smallcount);

System.out.println ("Number of Numbers:" +numbercount);

}

L Title Two: Converts the first letter in a string to uppercase, the other letters to lowercase, and prints the changed string.

L Idea: 1. Divide the string into two parts, the first part is the first letter in the string, and the second part is the remaining string.

2. Convert the first part of the string to uppercase, and the second part of the string to lowercase letters

3. Concatenate the two-part strings together to get a complete string

L Code:

public static string convert (String str) {

Get the first part into a string

String start = str.substring (0,1);

Get the second part into a string

String end = str.substring (1);

Converts the first part of a string into uppercase letters, converting the second part of the string to lowercase

String big = Start.touppercase ();

String small = end.tolowercase ();

Concatenate the two-part strings together to get a complete string

return big+small;

}

L Title three: Query the large string, the number of times the specified small string occurs. The number of times "Java" is queried in "Hellojava,nihaojava,javazhenbang".

L thought: 1. In a large string, find the location of the small string, the number of occurrences +1

2. Continue looking after the last occurrence of a small string, and you need to change the contents of the large string to the last query.

3. Go back to the first step and continue to find the location of the small string until the string is not queried.

L Code:

public static int GetCount (string big, string small) {

int count = 0; Number of occurrences of a small string

int index = -1;//where a small string appears

/*

The loop condition of the while is three steps:

Step one. Big.indexof (small) Gets the position of a small string that appears in a large string

Step two. Assigns the position of the small string to the variable index

Step three. Determine if the position appears to be-1, if the position equals-1, the large string has not been queried the small string, if the position is not equal to 1, then the loop, the number of times completed and modify the operation of a large string

*/

while (index = big.indexof (small))! =-1) {

count++;//Number of occurrences +1

Change a large string of content

Big = big.substring (index+1);

}

return count;

}

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.