Documentation

The Java™ Tutorials
Hide TOC
Strings字符串
Trail: Learning the Java Language
Lesson: Numbers and Strings

Strings字符串

Strings, which are widely used in Java programming, are a sequence of characters.字符串是一个字符序列,在Java编程中被广泛使用。In the Java programming language, strings are objects.在Java编程语言中,字符串是对象。

The Java platform provides the String class to create and manipulate strings.Java平台提供了String类来创建和操作字符串。

Creating Strings创建字符串

The most direct way to create a string is to write:创建字符串最直接的方法是写入:

String greeting = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes.在本例中,“你好,世界!”是字符串文本—代码中用双引号括起来的一系列字符。Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world!.每当它在代码中遇到字符串文字时,编译器就会创建一个String对象,在这种情况下,其值为—Hello world!

As with any other object, you can create String objects by using the new keyword and a constructor.与任何其他对象一样,可以使用new关键字和构造函数创建String对象。The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:String类有13个构造函数,允许您使用不同的源(例如字符数组)提供字符串的初始值:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.此代码段的最后一行显示hello


Note: The String class is immutable, so that once it is created a String object cannot be changed.String类是不可变的,因此一旦创建了String对象,就不能对其进行更改。The String class has a number of methods, some of which will be discussed below, that appear to modify strings.String类有许多方法,下面将讨论其中一些方法,它们似乎可以修改字符串。Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.由于字符串是不可变的,这些方法真正做的是创建并返回一个包含操作结果的新字符串。

String Length字符串长度

Methods used to obtain information about an object are known as accessor methods.用于获取对象信息的方法称为访问器方法One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.可以用于字符串的一个访问器方法是length()方法,它返回字符串对象中包含的字符数。After the following two lines of code have been executed, len equals 17:执行以下两行代码后,len等于17:

String palindrome = "Dot saw I was Tod";
int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation.回文是一个对称的单词或句子—它前后拼写相同,忽略大小写和标点符号。Here is a short and inefficient program to reverse a palindrome string.下面是一个简短而低效的程序来反转回文字符串。It invokes the String method charAt(i), which returns the ith character in the string, counting from 0.它调用String方法charAt(i),该方法返回字符串中的第i个字符,从0开始计数。

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Running the program produces this output:运行该程序会产生以下输出:

doT saw I was toD

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string.为了完成字符串反转,程序必须将字符串转换为字符数组(第一个for循环),将数组反转为第二个数组(第二个for循环),然后再转换回字符串。The String class includes a method, getChars(), to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above withString类包括一个getChars()方法,用于将字符串或字符串的一部分转换为字符数组,所以我们可以将上面程序中的第一个for循环替换为

palindrome.getChars(0, len, tempCharArray, 0);

Concatenating Strings连接字符串

The String class includes a method for concatenating two strings:String类包括一个用于连接两个字符串的方法:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end.这将返回一个新字符串,该字符串为string1,并在末尾添加string2

You can also use the concat() method with string literals, as in:您还可以将concat()方法用于字符串文本,如中所示:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in字符串通常使用+运算符连接,如下所示

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

which results in导致

"Hello, world!"

The + operator is widely used in print statements.+运算符广泛用于打印语句。For example:例如:

String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");

which prints打印了

Dot saw I was Tod

Such a concatenation can be a mixture of any objects.这种连接可以是任何对象的混合。For each object that is not a String, its toString() method is called to convert it to a String.对于每个不是String的对象,调用其toString()方法将其转换为字符串。


Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string.Java编程语言不允许文本字符串跨越源文件中的行,因此必须在多行字符串的每行末尾使用+串联运算符。For example:例如:
String quote = 
    "Now is the time for all good " +
    "men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.print语句中,使用+串联运算符在行之间断开字符串再次非常常见。


Creating Format Strings创建格式字符串

You have seen the use of the printf() and format() methods to print output with formatted numbers.您已经看到了使用printf()format()方法打印带格式数字的输出。The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.String类有一个等价的类方法format(),它返回一个String对象而不是PrintStream对象。

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement.使用String的静态format()方法可以创建可重用的格式化字符串,而不是一次性打印语句。For example, instead of例如,代替

System.out.printf("The value of the float " +
                  "variable is %f, while " +
                  "the value of the " + 
                  "integer variable is %d, " +
                  "and the string is %s", 
                  floatVar, intVar, stringVar);

you can write你可以写

String fs;
fs = String.format("The value of the float " +
                   "variable is %f, while " +
                   "the value of the " + 
                   "integer variable is %d, " +
                   " and the string is %s",
                   floatVar, intVar, stringVar);
System.out.println(fs);

Previous page: Characters
Next page: Converting Between Numbers and Strings