Java如何使用CharacterIterator反转字符串?
在此示例中,我们使用java.text.CharacterIterator实现类java.text.StringCharacterIterator来反转字符串。通过从最后一个索引到字符串的开头读取字符串来完成此操作。
package org.nhooo.example.text; import java.text.CharacterIterator; import java.text.StringCharacterIterator; public class StringCharacterIteratorReverseExample { private static final String text = "Jackdaws love my big sphinx of quartz"; public static void main(String[] args) { CharacterIterator it = new StringCharacterIterator(text); System.out.println("Before = " + text); System.out.print("After = "); //从最后一个索引到开始迭代一个字符串。 for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it.previous()) { System.out.print(ch); } } }
上面的代码片段的结果:
Before = Jackdaws love my big sphinx of quartz After = ztrauq fo xnihps gib ym evol swadkcaJ