Ryan
Ryan

Reputation: 83

Skip non-alphabetical characters with BreakIterator

My goal from this is to convert "<,Bold,>" to "< Bold>" (Without the space between '<' & 'B') using BreakIterator

Say String " This is a test." is my input

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) returns <,Bold,>, ,This, ,is, ,a, ,test.

I've tried :

            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);

All that returns is Char Not Skipped.

Upvotes: 0

Views: 89

Answers (1)

Felix Gerber
Felix Gerber

Reputation: 1651

I'm not sure if I got your question the right way.

If you want to delet all , in your string you could easily do:

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

The output would look like that:

This is a test

If you just want to delet <, and ,> you could use:

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

Output of that would be

<Bold>, ,This, ,is, ,a, ,test

Upvotes: 1

Related Questions