2014-11-03 21 views
1

我可以创造一个AttributedString像这样:从AttributedString获取文本(纯字符串) - 怎么做,为什么这么难?

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

直接的问题 - 我怎么可以从AttributedString对象的基础文本(“世界你好”)?

as.toString()产生字符串 “[email protected]

我在AttributedString.class这个信息被存储看到,但故意private--

所有(与长度除外)读操作是私人的,因为AttributedString实例通过迭代器访问

所以看起来像我需要使用as.getIterator()得到一个AttributedCharacterIterator并迭代它来产生底层字符串?这是最好的方法,为什么这些信息是无法访问的?

+0

为什么要这么做? – biziclop 2014-11-03 20:41:02

+0

@AJPerez,谢谢你的提示,标签已移除。 – 2014-11-03 20:47:34

+0

@biziclop,我有一个接受AttributedString的呈现方法,但我也需要关于底层字符串的信息。要求String和AttributedString作为参数似乎很愚蠢......? – 2014-11-03 20:51:35

回答

3

嗯,这是实际的代码做什么你问:

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()方法:

创建一个AttributedCharacterIterator实例,用于访问此字符串的全部内容。

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

+0

一个不幸的现实,但你真的回答了这个问题,所以谢谢! – 2014-11-03 21:20:31

+0

@stu没问题。 – Azar 2014-11-03 21:23:43

0
public static String getString(AttributedString attributedString){ 
     AttributedCharacterIterator it = attributedString.getIterator(); 
     StringBuilder stringBuilder = new StringBuilder(); 

     char ch = it.current(); 
     while(ch != CharacterIterator.DONE) 
     { 
      stringBuilder.append(ch); 
      ch = it.next(); 
     } 
     return stringBuilder.toString(); 
    }