Java entry (5) -- String/string class, entry String

Source: Internet
Author: User

Java entry (5) -- String/string class, entry String

In the previous example, there was a String example. Some friends certainly didn't know what to do. In fact, the String class is a special class in Java, namely the String class. It is not one of the basic data types in Java, but can be used like the basic data type, declarations are the same as initialization operations and are the objects that the program often processes. Therefore, it is important to learn how to use String well.

1. Create a string

In Java, the String class constructor is used to create String variables. The common constructor is as follows:

  1. Use the String () method to initialize a newly created String object.

String s = new String();

  2. Use the String (char a []) method to create a String object.

char a[] = {'h','e','l','l','o'};
String s = new String(a);

The above code is equivalent to String s = new String ("hello ");

  3. Use the String (char a [], int offset, int length) method to create an object.

char a[] = {'s','t','u','d','e','n','t'};String s = new String(a, 2, 4);

The above code is equivalent to String s = new String ("uden ");. Offset indicates the position where the string is intercepted (starting from 0), and length indicates the truncation length. Therefore, this example indicates that the truncation starts from the 'U' element marked as 2 in array a and the truncation length is 4. Therefore, the truncated string is "uden ".

In general, you can also directly declare: String s = "We are Students ";

Ii. String operations

You can perform operations on declared strings.

1. String connection

When multiple strings are connected, "+" is used to connect each two connected strings. "+" is the connector of the string, and a new string is generated after the connection.

char a[] = {'s','t','u','d','e','n','t'};
String s = new String(a, 2, 4);

This method has also appeared many times in the previous example. s1, space, and s2 are connected, and the running result is "hello world ".

When a string is connected to other data types, the "+" connector is also used, and the returned value after the connection is a string.

String s1 = new String("hello");
String s2 = new String("world");
String  s = s1 + " " + s2;

When a string is too long, you can use "+" to write it in two rows.

2. Obtain string Information

To operate a String, we first need to know its length. We can use the length () method of the String class to obtain the length of the declared String object.

String s = "We are students"; System. out. println ("the length of the String is:" + s. length ());

The running result of the above Code is 15, and it is obvious that spaces are also included. This should be noted.

In addition to the length, we need to obtain the string information, and the index location. When we need a character of a string, we need to obtain it through the index location. The indexOf () and lastIndexOf () methods are provided in the String class to obtain the index location of the specified character. The difference is that the former returns the index of the first position of the character to be searched, and the latter returns the index of the last position of the character to be searched.

String str = "We are students";
System.out.println (str.indexOf ("s")); // index of the first occurrence of s
System.out.println (str.lastIndexOf ("s")); // index of the last occurrence of s

The running result is 7 and 14. The storage status of str is as follows:

W E   A R E   S T U D E N T S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Of course, we can also get the characters at the specified index position. Use the charAt () method in the String class to return the character index, for example:

String s = "hello world";char a = s.charAt(6);

The value of character a is w.

3. Remove spaces from the string

For a string, you may need to remove internal spaces to complete some operations. There are two types of Remove string spaces. One is to remove leading and trailing spaces of the string, the other is to remove all spaces in the string, which can be implemented in different ways.

The trim () method is used to remove leading and trailing spaces of a string, as follows:

String s1 = "    hello world    ";String s2 = s1.trim();

After running, s2 becomes "hello world". This method only removes leading spaces and trailing spaces, but does not remove intermediate spaces.

To remove all spaces, use the StringTokenizer () and replaceAll () methods. For more information about the usage method, see Java API. The syntax format of the two methods is as follows:

StringTokenizer(String str, String delim)str.replaceAll(String regex, String replacement)
4. String replacement

String replacement is a new string that replaces the string at the specified position in the original string and generates a new string, which can be achieved through replace (), replaceFirst (), and other methods.

String s = "bad bad study";
String s1 = s.replace("bad","good");
String s2 = s.replaceFirst("bad","good");

The above code s1 and s2 are the new strings obtained using the replace () and replaceFirst () methods. The s1 value is "good study ", the value of s2 is "good bad study ". Here we can easily find the differences between them. The replace () method is to replace all the strings to be replaced in the original string, and replaceFirst () the method replaces only the first string to be replaced.

5. Judge the string

Judging a string is an important knowledge point, because we often need to judge whether two strings are equal and return its boolean value. The most common problem here isIt is wrong to use "=" to determine whether the string is equal.Because the comparison operator "=" compares memory locations and is not suitable for comparing strings. So what should I use to compare strings?

Two methods are used to determine whether the string is equal: equals () and equalsIgnoreCase (). The difference is that the former is case sensitive, while the latter is case insensitive. Let's give an example:

 1 public class Opinion {
 3     public static void main(String[] args) {
 4         String s1 = new String("");
 5         String s2 = new String("");
 6         String s3 = new String("HTTP://WWW.CNBLOGS.COM/ADAMJWH/");
 7         String s4 = s1;
 9         System.out.println("s1 == s2 : " + (s1 == s2));
10         System.out.println("s1 == s4 : " + (s1 == s4));
11         System.out.println("s1.equals(s2) : " + s1.equals(s2));
12         System.out.println("s1.equals(s3) : " + s1.equals(s3));
13         System.out.println("s1.equalsIgnoreCase(s2) : " + s1.equalsIgnoreCase(s2));
14         System.out.println("s1.equalsIgnoreCase(s3) : " + s1.equalsIgnoreCase(s3));
15     }
17 }

The running result is as follows:

Now let's analyze this code. First, we define two string types of variables s1 and s2, and assign two identical values (note that the values are the same ), then, an s3 is defined as s1 in an upper case to compare the differences between the two methods. Then, an s4 is defined and s1 is assigned to it, indicating that s1 and s4 have the same value. First, we use the comparison operator "=" to compare s1, s2, s1, and s4. The result is that s1 is not equal to s2 but s4. Why? As mentioned above,The comparison operator "=" compares memory locationsThis is related to the String storage mechanism of Java. The data of basic types of variables and object references are all placed in the stack, the object itself is placed in the heap, and the explicit String constant is placed in the constant pool, the String object is placed in the heap, so the above results are obtained. Friends who are not familiar with the above can search for information about String storage in Java. The comparison between the equals () and the equalsIgnoreCase () methods is not much said. The result is obvious. The difference between the two methods is case sensitive.

The stratsWith () and endsWith () methods are also provided in the String class to determine whether the String starts and ends with the specified content. The return values are of the boolean type. For details, see the API, I will not go into detail here.

6. case-insensitive conversion of letters

The String class also provides a case-insensitive Conversion Method for letters, namely, toLowerCase () and toUpperCase (). The syntax format is as follows:


When toLowerCase () and toUpperCase () methods are used for case conversion, numbers or non-characters are not affected.

7. string segmentation

The split () method separates strings Based on the specified delimiter and stores the split results in the string array. It provides two methods of overloading: one is completely split and the other is to limit the number of parts to be split. The example is as follows:

String s = new String ("abc, def, ghi, jkl");
String [] s1 = s.split (","); // split string based on ","
String [] s2 = s.split (",", 2); // split string according to ",", split into 2

S1 and s2 are the arrays obtained by splitting strings in two ways. The elements in the s1 array are "abc", "def", "ghi", and "jkl". Because s2 has two split scores, therefore, the elements in the s2 array are "abc", "def, ghi, and jkl ". To define multiple separators, use "| ".

3. format strings

Formatting strings are commonly used in programs. They mainly include date formatting, time formatting, date/time combination formatting, and regular formatting.

The format () method is mainly used. This part of content is not described in detail. When using it in a program, you only need to check the API for calling and do not need to remember it too much.

Iv. Regular Expressions

Many friends may have heard about regular expressions, or those who have written script languages should have learned how to use regular expressions. So what is a regular expression?

In programming, you often need to check the input data. In this case, this expression is used. If a regular expression is matched, the data format is correct. Otherwise, the format is incorrect.

The content of regular expressions is not very important for beginners of Java. Generally, it is rarely used for Java regular expressions, in most cases, when a regular expression is developed at the backend of Java, the front-end must judge and process the input data. It may use JavaScript to write a regular expression, or directly embed a regular expression in HTML. There are also a lot of information about regular expressions on the Internet. If you really want to write it, you can't finish it at half past one, so I won't go into detail here, for more information, see

V. String Generator

The string generator, also known as the StringBuilder class, is an important common class of strings. The initial capacity of the newly created StringBuilder object is 16 characters. You can specify the initial length or dynamically edit strings such as adding, deleting, and inserting, this greatly improves the efficiency of frequently increasing strings.

1. StringBuilder class

Speaking of StringBuilder, we have to talk about StringBuffer. The StringBuilder class is a variable character sequence. It provides an API compatible with the StringBuffer class, but does not guarantee synchronization with it. This class is a simple replacement of the StringBuffer class, when the String cache is used by a single thread, it is faster than the StringBuffer class. However, if the StrinBuilder instance is used for multiple threads, it is not safe to use the StringBuffer class. In short, StringBuilder is more efficient than StringBuffer, but StringBuilder is insecure in multithreading, while StringBuffer is safer, but the efficiency of the two is higher than that of String.

2. Common StringBuilder class methods

The StringBuilder class has many constructor methods, including append, insert, and delete. The constructor is as follows:

builder.append(String str);
builder.append(StringBuffer sb);
builder.insert(int offset, String str);
builder.delete(int start, int end);

The append method is to append the string/String cache specified by the parameter to the string generator; the insert method is to add the string str specified by the parameter to the specified position offset; the delete method removes the substring at this position in the string generator from the specified start to the specified end.

The String class also has a common method toString (). This method is often used in the String generator to convert the String generator to a String. After conversion, the value of the String generator remains unchanged.

Only some common methods are listed here. For more information, see the java. lang. StringBuilder API documentation.

The above is the content about the strings in Java. Many Java-provided methods need to be queried in the API. In contrast, there are not many knowledge points, you need to understand the application of the String class. For the method, you can check the API during programming to call the corresponding method. However, you must master at least several common methods, such as equals () and length (), toString () method, and so on.

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: 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.