使用BreakIterator跳过非字母字符

时间:2015-12-01 13:18:00

标签: java

我的目标是转换"<,Bold,>"到"<粗体>" (使用BreakIterator时没有'' B')之间的空格

Say String"这是一个考验。"是我的输入

public static List<String> getWords(String text) {
    List<String> words = new ArrayList<String>();
    BreakIterator breakIterator = BreakIterator.getWordInstance();
    breakIterator.setText(text);
    int lastIndex = breakIterator.first();
    while (BreakIterator.DONE != lastIndex) {
        int firstIndex = lastIndex;
        lastIndex = breakIterator.next();
        if (lastIndex != BreakIterator.DONE) {
            String t = text.substring(firstIndex, lastIndex);
            words.add(t);
        }
    }
    return words;
}

getWords(String)返回&lt;,Bold,&gt;,这是,,,,,,,, test。

我试过了:

            String t = text.substring(firstIndex, lastIndex);
            if (t != "<" || t != ">" || t != "/" || t != ">") System.out.println("Char Not Skipped " + t); else System.out.println("Char Skipped" + t);
            //if (text.charAt (firstIndex - 1) == '<') t = "<" + t;
            //if (text.charAt (lastIndex + 1) == '>') t += ">";
            //if (text.charAt (lastIndex + 1) == '/' && text.charAt (lastIndex + 2) == '>') t += "/>";
            //System.out.println(t);
            words.add(t);

所有返回的是Char Not Skipped。

1 个答案:

答案 0 :(得分:1)

我不确定我的问题是否正确。

如果您想要删除字符串中的所有,,您可以轻松地执行此操作:

    String s = "<,Bold,>, ,This, ,is, ,a, ,test";
    String newString = s.replace(",", "");
    System.out.println(newString);

输出看起来像这样:

  

这是一个测试

如果您只想使用<,,>,可以使用:

   String s = "<,Bold,>, ,This, ,is, ,a, ,test";   
   String newString =  (s.replace("<,", "<")).replace(",>", ">");
   System.out.println(newString);

输出

  

<Bold> ,,,,,,,,,,,,,,