gpt4 book ai didi

java - 从 AttributedString 获取文本(纯字符串)——怎么做,为什么这么难?

转载 作者:行者123 更新时间:2023-11-29 05:15:28 25 4
gpt4 key购买 nike

我可以像这样创建一个 AttributedString:

AttributedString as = new AttributedString("Hello world"); 

简单明了的问题——如何从 AttributedString 对象中获取基础文本(“Hello world”)?

as.toString() 生成字符串“java.text.AttributedString@65f00565”

我在 AttributedString.class 中看到此信息已存储,但故意保密 --

all (with the exception of length) reading operations are private, since AttributedString instances are accessed through iterator

看来我需要使用 as.getIterator() 来获取 AttributedCharacterIterator 并迭代它以生成底层字符串?这是最好的方法吗?为什么这些信息如此难以访问?

最佳答案

好吧,这是执行您所要求的实际代码:

    AttributedString s = new AttributedString("Hello");
AttributedCharacterIterator x = s.getIterator();
String a = "";

a+=x.current();
while (x.getIndex() < x.getEndIndex())
a += x.next();
a=a.substring(0,a.length()-1);

System.out.println(a);

至于是否合适,我遵从AttributedString 的文档,特别是getIterator() 方法:

Creates an AttributedCharacterIterator instance that provides access to the entire contents of this string.

似乎没有其他方法可以访问实际的 String 内容。

关于java - 从 AttributedString 获取文本(纯字符串)——怎么做,为什么这么难?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com