Frage

Have posted below a method I've written for suffix replacement of string tokens.

public static String suffix_replacement(String string) {
    String[] tokens = string.split("\\s");
    String new_string = "";
    String suffix = "";
    String replacement = "";

    for (String token : tokens) {            
        suffix = GetElements.suffix_replacement_map.containsKey(getSuffix(token, 7)) ? getSuffix(token, 7) : 
                GetElements.suffix_replacement_map.containsKey(getSuffix(token, 6)) ? getSuffix(token, 6) : 
                GetElements.suffix_replacement_map.containsKey(getSuffix(token, 5)) ? getSuffix(token, 5) : 
                GetElements.suffix_replacement_map.containsKey(getSuffix(token, 4)) ? getSuffix(token, 4) : 
                GetElements.suffix_replacement_map.containsKey(getSuffix(token, 3)) ? getSuffix(token, 3) : "";  

        replacement = suffix.equals("") ? "" : GetElements.suffix_replacement_map.get(suffix);

        if (!suffix.equals("")) 
            token = token.substring(0, token.length()-suffix.length())+replacement;

        new_string += token+" ";
    }

    new_string = new_string.trim();

    if (!new_string.equals(string)) {
        System.out.println(string);
        System.out.println(new_string);
    }        
    return new_string;
}

Test case 1

string: hemisphere hemorrhage

new_string: hemisphere hemorrh

It works fine.

Test case 2:

string: cardiac arrhythmia

new_string: arrhythmia

It does not give desired string.

The function seems to return incorrect Strings if any token other than the last token in the String gets a suffix replacement.

Appreciate any help with locating the bug in the function.

Thank you.


Added Info:

suffix_replacement_map is populated with contents below:

tic:sis
sis:tic
oneal:ineum
age:
cular:cal
cardiac:cardia
nic:nia
ages:ed
evi:evus
cular:cal
cardiac:cardia
nic:nia
ages:ed
evi:evus
tachy:tachicardia
cral:crum
cancer:carcinoma
sillar:sil

Function used:

public static String getSuffix(String str, int len) {
    if (str.length() < len) {
        return "";
    }
    return str.substring(str.length() - len);
}   
War es hilfreich?

Lösung

I implemented getSuffix by my own ideas:

   private static String getSuffix(String token, int i) {
        if (i <= token.length()) {
            return token.substring(token.length() - i, token.length());
        }
        return null;
    }

and it worked... :) could you add your version to the entry pls? I think something with the getToken could be buggy.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top