📌  相关文章
📜  Java中的 StringCharacterIterator current() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:16:26.929000             🧑  作者: Mango

Java中的StringCharacterIterator current()方法及示例

介绍

Java中的StringCharacterIterator是一个类,用于遍历字符串中每个字符的迭代器。它提供了访问字符串中的字符的方法,以及对字符串的修改方法。

current()方法是StringCharacterIterator类中的一个方法,它返回当前迭代器所在位置的字符。

语法
public char current()
参数

该方法没有参数。

返回值

当前迭代器所在位置的字符。

示例
import java.text.*;

public class StringCharacterIteratorExample {

    public static void main(String[] args) {
        
        // 创建一个StringCharacterIterator对象
        String str = "hello";
        StringCharacterIterator sci = new StringCharacterIterator(str);
        
        // 在字符串中迭代
        System.out.println("Iterating over string:");
        for(char c = sci.first(); c != StringCharacterIterator.DONE; c = sci.next()) {
            System.out.print(c + "\t");
        }
        System.out.println();
        
        // 返回当前字符,使用current()方法
        while(sci.current() != StringCharacterIterator.DONE) {
            System.out.print(sci.current() + "\t");
            sci.next();
        }
    }
}

输出:

Iterating over string:
h	e	l	l	o	
h	e	l	l	o	

程序中,我们首先创建了一个StringCharacterIterator对象,然后使用next()方法来迭代字符串中的每个字符。随后,我们再次使用current()方法来遍历字符串中的每个字符,并将其打印出来。

需要注意的是,使用current()方法时需要先调用一下next()方法,才能获取到第一个字符。另外,当该方法遍历到字符串的末尾时,它将返回字符DONE,值为'\uFFFF'。