集册 Java实例教程 迭代字符串的字符

迭代字符串的字符

欢马劈雪     最近更新时间:2020-01-02 10:19:05

585
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
迭代字符串的字符

import java.text.CharacterIterator;

import java.text.StringCharacterIterator;
/** from 
n o w  j a v a  . c o m**/


public class Main {

  public static void main(String[] argv) {

    CharacterIterator it = new StringCharacterIterator("abcd");


    // Iterate over the characters in the forward direction

    for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {

      // Use ch ...

    }


    // Iterate over the characters in the backward direction

    for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it.previous()) {

      // Use ch ...

    }


    // Other methods

    char ch = it.first(); // a

    ch = it.current(); // a

    ch = it.next(); // b/* 来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

    ch = it.current(); // b

    System.out.println(ch);

    ch = it.last(); // d

    int pos = it.getIndex(); // 3

    System.out.println(ch);

    ch = it.next(); // DONE

    pos = it.getIndex(); // 4

    System.out.println(ch);

    ch = it.previous(); // d

    System.out.println(ch);

    ch = it.setIndex(1); // b


    // Change the characters

    ((StringCharacterIterator) it).setText("efgh");

    ch = it.current(); // e


    
展开阅读全文