How to Iterate Over the String Characters in Java – 如何在 Java 中遍历字符串中的字符

最后修改: 2023年 11月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll get familiar with the ways to iterate over the string characters along with their time and space complexity.

在本教程中,我们将熟悉遍历字符串字符的方法及其时间和空间复杂性。

2. Common Ways to Iterate Over a String

2.对 String 进行迭代的常见方法

In Java, there are several ways to iterate over the characters of a string, each with its own time and space complexity. The best method to use depends on the specific requirements of your program.

在 Java 中,有几种遍历字符串字符的方法,每种方法都有其时间和空间复杂性。使用哪种方法最好,取决于程序的具体要求。

2.1. for Loop

2.1.for循环

We can use a simple for loop to iterate over the characters of a string. This method has a time complexity of O(n), where n is the length of the string str, and a space complexity of O(1) because it only requires a single loop variable:

我们可以使用一个简单的 for 循环来遍历字符串中的字符。这种方法的时间复杂度为 O(n),其中 n 是字符串 str 的长度,空间复杂度为 O(1),因为它只需要一个循环变量:

String str = "Hello, Baeldung!";
for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i); 
    System.out.print(c)
}

2.2. toCharArray()

2.2.toCharArray()

The toCharArray() method first converts the string into a character array, which we can use to perform the iteration. This method has a time complexity of O(n), where n is the length of the string str, and a space complexity of O(n) because it creates a new char array:

toCharArray()方法首先将字符串转换为字符数组,我们可以使用该数组执行迭代。该方法的时间复杂度为 O(n),其中 n 是字符串 str 的长度,空间复杂度为 O(n),因为它创建了一个新的字符数组:

String str = "Hello, Baeldung!"; 
for (char c : str.toCharArray()) { 
    System.out.print(c);
}

2.3. Java 8 Stream

2.3 Java 8 数据流

We can use Java 8 Streams to process each character in the string. This approach has a time complexity of O(n) and a space complexity that depends on the intermediate operations you perform on the stream:

我们可以使用 Java 8 Streams 来处理字符串中的每个字符。这种方法的时间复杂度为 O(n),空间复杂度取决于您在流上执行的中间操作:

String str = "Hello, Baeldung!"; 
str.chars().forEach(c -> { 
    System.out.print((char) c);
});

Note that in the above code, we need to typecast the variable c to char because chars() returns an IntStream.

请注意,在上述代码中,我们需要将变量 c 类型转换为 char ,因为 chars() 返回一个 IntStream.

2.4. CharacterIterator

2.4.字符迭代器</em

We utilize the following methods of CharacterIterator methods to iterate over the String.

我们使用以下 CharacterIterator 方法遍历字符串。

  • current(): to get the current character
  • next(): to move forward by one position

StringCharacterIterator provides the implementation of CharacterIterator. This interface allows to have bidirectional iteration over the string. The iterator iterates over a bounded sequence of characters. Iterators maintain a current character index whose valid range is from getBeginIndex() to getEndIndex().

StringCharacterIterator 提供了 CharacterIterator 的实现。该接口允许对字符串进行双向迭代。迭代器对有界字符序列进行迭代。迭代器维护当前字符索引,其有效范围是从getBeginIndex()getEndIndex()。</em

Here, the time complexity is O(n), where n is the length of the string str, and a space complexity of O(1) because it only requires a single while loop iterator:

这里的时间复杂度为 O(n),其中 n 是字符串 str 的长度,空间复杂度为 O(1),因为它只需要一个 while 循环迭代器:

String str = "Hello, Baeldung!";
CharacterIterator it = new StringCharacterIterator(str);
while (it.current() != CharacterIterator.DONE) {
    System.out.print(it.current());
    it.next();
}

3. Conclusion

3.结论

The best method to use depends on our specific use case. For most cases, the simple for loop or the enhanced for loop is the most straightforward and efficient way to iterate over characters in a string. They have a low space complexity and a time complexity of O(n), which is the best we can achieve for this task.

最佳方法取决于我们的具体使用情况。在大多数情况下,简单的 for 循环或增强的 for 循环是遍历字符串中字符的最直接、最高效的方法。它们的空间复杂度和时间复杂度都很低,分别为O(n),这是我们在这项任务中所能达到的最佳水平。

We can use Java 8 Streams when we need to perform complex operations on the characters or if we want to take advantage of the functional programming capabilities it provides.

如果我们需要对字符执行复杂的操作,或者想利用 Java 8 提供的函数式编程功能,就可以使用 Java 8 Streams。

As usual, the source code of all these examples is available over on GitHub.

像往常一样,所有这些示例的源代码都可以在 GitHub 上获取