Documentation

The Java™ Tutorials
Hide TOC
Manipulating Characters in a String处理字符串中的字符
Trail: Learning the Java Language
Lesson: Numbers and Strings
Section: Strings

Manipulating Characters in a String处理字符串中的字符

The String class has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing case, and other tasks.String类有许多方法用于检查字符串的内容、查找字符串中的字符或子字符串、更改大小写以及其他任务。

Getting Characters and Substrings by Index通过索引获取字符和子字符串

You can get the character at a particular index within a string by invoking the charAt() accessor method.通过调用charAt()访问器方法,可以获取字符串中特定索引处的字符。The index of the first character is 0, while the index of the last character is length()-1.第一个字符的索引为0,而最后一个字符的索引为length()-1For example, the following code gets the character at index 9 in a string例如,以下代码获取字符串中索引9处的字符:

String anotherPalindrome = "Niagara. O roar again!"; 
char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:索引从0开始,因此索引9处的字符为“O”,如下图所示:

Use the charAt method to get a character at a particular index.

If you want to get more than one consecutive character from a string, you can use the substring method.如果要从字符串中获取多个连续字符,可以使用substring方法。The substring method has two versions, as shown in the following table:substring方法有两个版本,如下表所示:

The substring Methods in the String ClassString类中的substring方法
Method方法 Description描述
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.返回作为此字符串的子字符串的新字符串。The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.子字符串从指定的beginIndex开始,并延伸到索引endIndex-1处的字符。
String substring(int beginIndex) Returns a new string that is a substring of this string.返回作为此字符串的子字符串的新字符串。The integer argument specifies the index of the first character.整数参数指定第一个字符的索引。Here, the returned substring extends to the end of the original string.在这里,返回的子字符串扩展到原始字符串的末尾。

The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word "roar":下面的代码来自Niagara回文,它是从索引11扩展到但不包括索引15的子字符串,索引15是单词“roar”:

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15);
Use the substring method to get part of a string.

Other Methods for Manipulating Strings操作字符串的其他方法

Here are several other String methods for manipulating strings:以下是用于操作字符串的其他几种String方法:

Other Methods in the String Class for Manipulating StringsString类中用于操作字符串的其他方法
Method方法 Description描述
String[] split(String regex)
String[] split(String regex, int limit)
Searches for a match as specified by the string argument (which contains a regular expression) and splits this string into an array of strings accordingly.搜索字符串参数(包含正则表达式)指定的匹配项,并相应地将该字符串拆分为字符串数组。The optional integer argument specifies the maximum size of the returned array.可选整数参数指定返回数组的最大大小。Regular expressions are covered in the lesson titled "Regular Expressions."“正则表达式”课程将介绍正则表达式
CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence constructed from beginIndex index up until endIndex - 1.返回从beginIndex索引到endIndex-1构造的新字符序列。
String trim() Returns a copy of this string with leading and trailing white space removed.返回此字符串的副本,其中前导和尾随空格已删除。
String toLowerCase()
String toUpperCase()
Returns a copy of this string converted to lowercase or uppercase.返回此字符串转换为小写或大写的副本。If no conversions are necessary, these methods return the original string.如果不需要转换,这些方法将返回原始字符串。

Searching for Characters and Substrings in a String搜索字符串中的字符和子字符串

Here are some other String methods for finding characters or substrings within a string.下面是一些用于查找字符串中的字符或子字符串的其他String方法。The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().String类提供了访问器方法,用于返回特定字符或子字符串在字符串中的位置:indexOf()lastIndexOf()The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string.indexOf()方法从字符串的开头向前搜索,lastIndexOf()方法从字符串的结尾向后搜索。If a character or substring is not found, indexOf() and lastIndexOf() return -1.如果未找到字符或子字符串,indexOf()lastIndexOf()将返回-1

The String class also provides a search method, contains, that returns true if the string contains a particular character sequence.String类还提供了一个搜索方法contains,如果字符串包含特定的字符序列,该方法将返回trueUse this method when you only need to know that the string contains a character sequence, but the precise location isn't important.当您只需要知道字符串包含字符序列,但精确位置并不重要时,请使用此方法。

The following table describes the various string search methods.下表介绍了各种字符串搜索方法。

The Search Methods in the String ClassString类中的搜索方法
Method方法 Description描述
int indexOf(int ch)
int lastIndexOf(int ch)
Returns the index of the first (last) occurrence of the specified character.返回指定字符第一次(最后一次)出现的索引。
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.返回指定字符第一次(最后一次)出现的索引,从指定索引向前(向后)搜索。
int indexOf(String str)
int lastIndexOf(String str)
Returns the index of the first (last) occurrence of the specified substring.返回指定子字符串第一次(最后一次)出现的索引。
int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index.返回指定子字符串第一次(最后一次)出现的索引,从指定索引向前(向后)搜索。
boolean contains(CharSequence s) Returns true if the string contains the specified character sequence.如果字符串包含指定的字符序列,则返回true

Note: CharSequence is an interface that is implemented by the String class.CharSequence是由String类实现的接口。Therefore, you can use a string as an argument for the contains() method.因此,可以使用字符串作为contains()方法的参数。

Replacing Characters and Substrings into a String将字符和子字符串替换为字符串

The String class has very few methods for inserting characters or substrings into a string.String类很少有将字符或子字符串插入字符串的方法。In general, they are not needed: You can create a new string by concatenation of substrings you have removed from a string with the substring that you want to insert.通常,它们是不需要的:您可以通过将从字符串中删除的子字符串与要插入的子字符串连接起来来创建新字符串。

The String class does have four methods for replacing found characters or substrings, however.但是,String类有四种方法来替换找到的字符或子字符串。They are:他们是:

Methods in the String Class for Manipulating StringsString类中用于操作字符串的方法
Method方法 Description描述
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.返回一个新字符串,该字符串由newChar替换该字符串中所有出现的oldChar生成。
String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.用指定的文字替换序列替换与文字目标序列匹配的此字符串的每个子字符串。
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.将此字符串中与给定正则表达式匹配的每个子字符串替换为给定替换。
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.将此字符串中与给定正则表达式匹配的第一个子字符串替换为给定替换。

An Example一个例子

The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate different parts of a file name.下面的类Filename说明了如何使用lastIndexOf()substring()来隔离文件名的不同部分。


Note: The methods in the following Filename class don't do any error checking and assume that their argument contains a full directory path and a filename with an extension.以下Filename类中的方法不进行任何错误检查,并假定其参数包含完整的目录路径和带有扩展名的文件名。If these methods were production code, they would verify that their arguments were properly constructed.如果这些方法是生产代码,它们将验证其参数是否正确构造。
public class Filename {
    private String fullPath;
    private char pathSeparator, 
                 extensionSeparator;

    public Filename(String str, char sep, char ext) {
        fullPath = str;
        pathSeparator = sep;
        extensionSeparator = ext;
    }

    public String extension() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        return fullPath.substring(dot + 1);
    }

    // gets filename without extension
    public String filename() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(sep + 1, dot);
    }

    public String path() {
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(0, sep);
    }
}

Here is a program, FilenameDemo, that constructs a Filename object and calls all of its methods:下面是一个名为FilenameDemo的程序,它构造一个Filename对象并调用其所有方法:

public class FilenameDemo {
    public static void main(String[] args) {
        final String FPATH = "/home/user/index.html";
        Filename myHomePage = new Filename(FPATH, '/', '.');
        System.out.println("Extension = " + myHomePage.extension());
        System.out.println("Filename = " + myHomePage.filename());
        System.out.println("Path = " + myHomePage.path());
    }
}

And here's the output from the program:下面是程序的输出:

Extension = html
Filename = index
Path = /home/user

As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name.如下图所示,我们的extension方法使用lastIndexOf来定位文件名中句点(.)的最后一次出现。Then substring uses the return value of lastIndexOf to extract the file name extension然后,substring使用lastIndexOf的返回值来提取文件扩展名that is, the substring from the period to the end of the string.也就是说,从句点到字符串末尾的子字符串。This code assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.此代码假定文件名中有句点;如果文件名没有句点,lastIndexOf返回-1substring方法抛出StringIndexOutOfBoundsException

The use of lastIndexOf and substring in the extension method in the Filename class.

Also, notice that the extension method uses dot + 1 as the argument to substring.另外,请注意extension方法使用dot+1作为substring的参数。If the period character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one larger than the largest index into the string (because indices start at 0).如果句点字符(.)是字符串的最后一个字符,则dot+1等于字符串的长度,该长度比字符串中的最大索引大1(因为索引从0开始)。This is a legal argument to substring because that method accepts an index equal to, but not greater than, the length of the string and interprets it to mean "the end of the string."这是substring的合法参数,因为该方法接受等于但不大于字符串长度的索引,并将其解释为“字符串的结尾”。


Previous page: Converting Between Numbers and Strings
Next page: Comparing Strings and Portions of Strings