Documentation

The Java™ Tutorials
Hide TOC
Summary of Characters and Strings字符和字符串的小结
Trail: Learning the Java Language
Lesson: Numbers and Strings
Section: Strings

Summary of Characters and Strings字符和字符串的小结

Most of the time, if you are using a single character value, you will use the primitive char type.大多数情况下,如果使用的是单个字符值,则将使用基本char类型。There are times, however, when you need to use a char as an object—for example, as a method argument where an object is expected.但是,有时需要将字符用作对象—例如,作为预期对象的方法参数。The Java programming language provides a wrapper class that "wraps" the char in a Character object for this purpose.Java编程语言提供了一个包装器类,用于为此目的将char“包装”到Character对象中。An object of type Character contains a single field whose type is char.Character类型的对象包含一个类型为char的字段。This Character class also offers a number of useful class (that is, static) methods for manipulating characters.这个Character类还提供了许多有用的类(即静态)方法来操作字符。

Strings are a sequence of characters and are widely used in Java programming.字符串是一个字符序列,在Java编程中被广泛使用。In the Java programming language, strings are objects.在Java编程语言中,字符串是对象。The String class has over 60 methods and 13 constructors.String类有60多种方法和13种构造函数。

Most commonly, you create a string with a statement like最常见的情况是,使用以下语句创建字符串

String s = "Hello world!";

rather than using one of the String constructors.而不是使用一个String构造函数。

The String class has many methods to find and retrieve substrings; these can then be easily reassembled into new strings using the + concatenation operator.String类有许多方法来查找和检索子字符串;然后可以使用+串联运算符轻松地将这些字符串重新组合成新字符串。

The String class also includes a number of utility methods, among them split(), toLowerCase(), toUpperCase(), and valueOf().String类还包括许多实用程序方法,其中包括split()toLowerCase()toUpperCase()valueOf()The latter method is indispensable in converting user input strings to numbers.在将用户输入字符串转换为数字时,后一种方法是必不可少的。The Number subclasses also have methods for converting strings to numbers and vice versa.Number子类也有将字符串转换为数字的方法,反之亦然。

In addition to the String class, there is also a StringBuilder class.除了String类之外,还有一个StringBuilder类。Working with StringBuilder objects can sometimes be more efficient than working with strings.使用StringBuilder对象有时比使用字符串更有效。The StringBuilder class offers a few methods that can be useful for strings, among them reverse().StringBuilder类提供了一些对字符串有用的方法,其中包括reverse()In general, however, the String class has a wider variety of methods.但是,一般来说,String类有更广泛的方法。

A string can be converted to a string builder using a StringBuilder constructor.可以使用StringBuilder构造函数将字符串转换为字符串生成器。A string builder can be converted to a string with the toString() method.可以使用toString()方法将字符串生成器转换为字符串。


Previous page: The StringBuilder Class
Next page: Autoboxing and Unboxing