简体   繁体   中英

Letters having the same equivalence

Looking ideas on how to go about accomplishing this. Basically I want certain characters to have equivalence.

For example: M = N

So: Mum = Nun

However: Mum can also equal Num.

I was advised to try a map of replacements and this worked until the third example where not all M's are to be changed to N's.

Thanks

This is the code for the map of replacements:

HashMap<String,String> replacements = new HashMap<>();
                replacements.put("n","m");
                replacements.put("m","n");

                String ignoreFirstChar = names[j].charAt(0) + (names[j].substring(1,names[j].length()).replaceAll("[^a-zA-Z]+", "").toLowerCase());

                String result = "";
                for(int i1 = 0; i1 < ignoreFirstChar.length(); i1++) {
                    String rpl = replacements.get(ignoreFirstChar.charAt(i1)+"");
                    result += rpl==null?ignoreFirstChar.charAt(i1):rpl;
                }


                System.out.println(ignoreFirstChar);
                System.out.println(result);

I assume M and m are not equivalent. Therefore, if M = N, we cannot say M = n. If you would like to use a "map of replacements" as you have been suggested, I would use it for the purpose of normalizing your strings.

You would take the current problem of

Given strings x and y, determine whether x equals y

and change it to

Given strings x and y, determine whether normalize(x) equals normalize(y)

The purpose of normalizing your strings is to apply any equivalence rules that you have, such as M = N. That way "Mum" would be converted to "Num", and then you can compare the two strings without having to worry about the rules because they've already been applied.

The normalize method would look something like

/* 
 * Takes each character in inStr and replaces them as necessary based on
 * your replacement map. For example, if you see an "n", then replace it with "m"
 */
String normalize(String inStr) {
   String newStr;

   // something happens

   return newStr;
}

If case-sensitivity is not important, then you would again normalize your strings by first converting them to lower-case or upper-case (doesn't matter, as long as it is consistent)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM